0

So this code doesn't print out the entries inside of the vector gameLibrary

Originally I just used the gameLibrary.pushback(" ") function to add them and that worked fine.

I'm more just trying to get to grips with why this doesn't work. when ( at least in my mind it's doing the same thing)

#include <iostream>
#include <vector>
#include <string>

using std::cout;
using std::vector;
using std::string;

void addGame(vector<string> gameLibrary, string gameName);

int main()
{
    vector<string> gameLibrary;
    vector<string>::iterator editIter;
    
    addGame(gameLibrary, "game");
    addGame(gameLibrary, "game 2");

    cout << "Your library: " << std::endl;

    for (editIter = gameLibrary.begin(); editIter != gameLibrary.end(); ++editIter)
    {
        cout << *editIter << std::endl;
    }
    
    return 0;
}


void addGame(vector<string>gameLibrary, string gameName)
{
    gameLibrary.emplace_back(gameName);
}
CGoodness
  • 3
  • 1

2 Answers2

0

addGame must not receive the vector it is filling by copy. It must be passed by reference or by pointer.

Exemple passing by reference :

void addGame(vector<string>& gameLibrary, string gameName)
{
    gameLibrary.emplace_back(gameName);
}

Otherwise, the copy is modified, so the vector declared in main is unchanged.

jpo38
  • 20,821
  • 10
  • 70
  • 151
0

Please read up on passing by value vs reference. In your function you are passing your array by value, which means that only the value of your array gets copied into the function.

Any changes to the array insider the function are not reflected back. If you need that, you need to pass your array by reference

see this answer : Are vectors passed to functions by value or by reference in C++

Manish Dash
  • 2,004
  • 10
  • 20