You are here:

C++/C++ vectors

Advertisement


Question
Hello, 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;
}


Answer
Hello,

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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.