C++/C++ vectors
Expert: Eddie - 9/24/2004
QuestionHello, I'm learning C++ by myself and have a problem with vectors. If we use one-dimensional array instead of a vector, this code works properly, but with a vector, vector elements will be all zeros when printed or summed. Please tell me why. Thanks in advance.
#include<iostream>
#include <vector>
using namespace std;
const r=10;
void createvector(vector <int> a)
{
for (int i=0;i<r;++i)
a[i]=i*3;
}
void printvector(vector <int> a)
{
cout<<'\n'<<"vector v = "<<"\n\n";
for (int i=0;i<r;++i)
cout<<"v["<<i<<"] = "<<a[i]<<'\t';
}
int sumvector(vector<int> a,int n)
{
int s = 0;
for (int i = 0; i < n; ++i)
s += a[i];
return s;
}
int main()
{
vector<int> vect(r);
createvector(vect);
printvector(vect);
cout<<"\nSum of elements of v: " <<
sumvector(vect,r);
return 0;
}
AnswerHello,
The reason your vector is printing out all zeros is because that when you call createvector(), you pass it a vector by copy. The compiler internally makes a copy of the parameter and modifies the copy. All you need to do is change the function prototype to take in a reference or a pointer, in which it changes the actual memory of the vector. I recommend a using a reference so you wouldn't have to actually change any internal function code:
void createvector(vector<int> &a);
Changing the prototypes to take in references will fix your problem.
I hope this information was helpful.
- Eddie