Array of C ++ vectors - curious behavior when adding elements

for google and stackoverflow search could not help me I have no choice but to ask you guys for help.

I would like to use an array of vectors - I know that this array should contain only two vectors. Thus,

vector<double> testVect[1]; 

Now, when I want to add an element to the first vector contained in the array, I use

 testVect[0].push_back(0); 

So far, everything looks fine - unfortunately, adding an element to the first vector somehow adds the same element to the second vector (in this case, 0).

Can someone tell me the reason for this behavior? (please) - and possibly a workaround. Currently, I have to use Visual Studio 6 (the employer will not install a new compiler - I am already heating up my colleagues: D

+8
c ++ arrays vector
source share
1 answer

If you need two vectors, you must declare:

  vector<double> testVect[2]; 

then use testVect[0] and testVect[1] in your code.

And you must include all warnings in your compiler.

BTW, you can install a recent Linux distribution with a recent GCC compiler (e.g. 4.7) and run it as g++ -Wall -g , it would probably warn you if you statically accessed testVect from outside, for example, it seems like you had .

Both GNU / Linux and GCC are free, so your manager can be happy.

+16
source share

All Articles