import { ItemCategory } from './ItemCategory';
export class HelloComponent {
@Input() name: string;
sample : ItemCategory;
}
我主要是这样:
struct Player {
int money=1500;
int position=1;
//Position positionn;
//int number; // number of player
bool eliminated =false;
};
1)如何存储for循环中的值?
2)如何将其放在单独的函数中,但仍将值传递到main中?
答案 0 :(得分:1)
您可以执行以下操作:
#include <iostream>
#include <vector>
#include "Player.hpp" // Your header file for Player struct.
int main()
{
std::cout << "Enter player quantity: ";
unsigned int quantity;
std::cin >> quantity;
std::vector<Player> game_players(quantity);
//...
return EXIT_SUCCESS;
}
请参阅std::vector
的构造函数。
编辑1-动态分配
如果不允许使用std::vector
或必须使用数组,则这是一种方法:
int main()
{
std::cout << "Enter player quantity: ";
unsigned int quantity_of_players;
std::cin >> quantity_of_players;
Player * p_players = new Player[quantity_of_players];
//...
delete [] p_players;
return 0;
}
上面的代码片段将播放器的容器分配到动态内存(也称为堆)中,因为数量未知。内存将被删除,然后返回操作系统。
编辑2:传递球员
您可以通过使用引用传递玩家的容器:
void Print_Player_Info(const std::vector<Player>& players)
{
for (unsigned int i = 0; i < players.size(); ++i)
{
std::cout << "Player " << i << ":\n";
std::cout << " money: " << players[i].money << "\n";
std::cout << "\n";
}
}