[英]How to use function variables in the main?
Hey i have a function that contains the STL container vector. 嘿,我有一个包含STL容器向量的函数。
void displayInventory()
{
vector<string> inventory;
cout<< "You have " << inventory.size() << " items.\n";
cout<< "\nYouritems:\n";
for (int i= 0; i< inventory.size(); ++i)
cout<< inventory[i] << endl;
}
And i wanna use the actual vector in another method play game. 我想在另一种方法玩游戏中使用实际矢量。
int playGame()
{
inventory.push_back("sword"); //This is an error. Expression must have class.
}
Can anyone help me do this without having to globalize the vector declaration ? 有人可以帮助我做到这一点而不必全局化向量声明吗?
Pass the vector by reference to the two functions and declare it in main? 通过引用将向量传递给两个函数,并在main中声明它?
int main()
{
vector<string> inventory;
playGame(inventory);
displayInventory(inventory);
}
void displayInventory(vector<string> &inventory)
{
inventory.push_back("string");
}
void playGame(vector<string> &inventory)
{
inventory.push_back("A second string");
}
You can receive it as a function parameter: 您可以将其作为函数参数接收:
int playGame(vector<string>& inventory)
{
inventory.push_back("sword");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.