1

I'm trying to change the data inside a vector's element by using a function. It happens that the elements are changed just inside the function. How can I keep the changings outside the function? Do I must use pointers?

The code:

#include <iostream>
#include <vector>

using namespace std;

void populate( int size_, vector<int> pop)
{
    //Set the vector's size and populate the vector
    pop.resize(size_);
    for(int i = 0; i<3 ; i++)
    {
        pop[i] = i;
    }
}

int main()
{
    vector<int> vec;
    int size = 3;
    populate(size, vec);

    for(vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
    {
        cout << *it << endl;
    }   
}

The output at cout should be : 0 1 2 But it is empty.

user3348949
  • 304
  • 3
  • 4
  • 15
  • 4
    Your function looks like it should be building and returning a vector, rather than taking one as a parameter. – juanchopanza Feb 27 '15 at 17:02
  • just recently I tried to explain something related to a friend and I made up [this example](http://stackoverflow.com/questions/28716209/what-operators-do-i-have-to-overload-to-see-all-operations-when-passing-an-objec). When you run this you can see how the object you are passing is copied to a local variable and that this local variable is deleted once the function returns. – 463035818_is_not_an_ai Feb 27 '15 at 17:05

3 Answers3

3

What you're trying to do is easily and idiomaticaly done with standard library facilities:

int size = 3;
std::vector<int> vec(size);
std::iota(vec.begin(), vec.end(), 0);  // include algorithm for this
jrok
  • 54,456
  • 9
  • 109
  • 141
  • I would +1 for promoting the use of std algorithms (because not so long time ago I had a hard time to get used to it) but I think the actual problem is that he is not aware of the concept of passing by reference – 463035818_is_not_an_ai Feb 27 '15 at 17:17
  • @tobi303 right but other users took care of explaining that. – jrok Feb 27 '15 at 17:21
2

You need to take the vector by reference

void populate( int size_, vector<int>& pop)

Otherwise you are passing in a copy of the vector, populating it, then returning, but the original vector is unmodified.

Or as @juanchopanza recommended, since the sole purpose of this function is to make this vector for you, it could be

vector<int> populate( int size_ )
{
    vector<int> temp(size_);
    for(int i = 0; i < size_ ; i++)
    {
        pop[i] = i;
    }
    return temp;
}

Then

int main()
{
    int size = 3;
    vector<int> vec = populate(size, vec);
    for(vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
    {
        cout << *it << endl;
    }   
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

You are sending in the vector to populate by value. This creates a copy, so pop is a copy of vec. Changes you make only affect pop.

Steven Lu
  • 41,389
  • 58
  • 210
  • 364