-1

嘿,我有一个包含 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;
}

我想在另一种方法玩游戏中使用实际向量。

int playGame()
{
    inventory.push_back("sword"); //This is an error. Expression must have class.
}

谁能帮我做到这一点而不必全球化矢量声明?

4

2 回答 2

3

通过引用这两个函数来传递向量并在 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");
}
于 2012-10-05T12:59:47.437 回答
2

您可以将其作为函数参数接收:

int playGame(vector<string>& inventory)
{
    inventory.push_back("sword");
}
于 2012-10-05T12:57:34.160 回答