You are here:

C++/C++ vector

Advertisement


Question
/*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>
const r=10;
using namespace std;
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
Sobhi , Thank you for your question.

I regret that I am unable to do debugging for people due to the volume of questions received. This kind of problem is usually easy to solve by stepping through the code with your debugger, looking at the values of the variables until you see something wrong. This should show you the exact line of the bug.

David Spector

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


David Spector

Expertise

Highly knowledgeable in the C++ language, Visual C++ (MSVC), Windows API, documentation and other quality-assurance techniques, and debugging. Knowledgeable in MFC, COM, GUI design, and object-oriented design.

Experience

I have been a software engineer since 1965. I have been published. My specializations have been: biomedical programming, compiler implementation, and many kinds of Windows programming. I don't do Databases or other business-oriented stuff.

Publications
Windows?/DOS Developer's Journal, ACM SIGPLAN Notices, and Computer Science Press.

Education/Credentials
ICCP Systems Programming Certification
Master's degree equivalent in Computer Science

©2016 About.com. All rights reserved.