简体   繁体   中英

How to use function variables in the main?

Hey i have a function that contains the STL container vector.

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?

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM