Reputation: 344
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.
Upvotes: 1
Views: 175
Reputation: 55395
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
Upvotes: 3
Reputation: 117866
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;
}
}
Upvotes: 2
Reputation: 43427
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
.
Upvotes: 0