Andrey Lujankin Andrey Lujankin - 19 days ago 4x
C++ Question

Array of Vectors C++ - curious behaviour 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 will only have to contain 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


So far everything seems ok - unfortunately adding an Element to the first vector somehow also adds the same element (in this case the 0) to the second vector as well.

Could anybody tell me the reason for this kind of behaviour ? (please) - and perhaps a workaround.
Currently I have to use Visual Studio 6 (employer won't install a new compiler - I am already riling up my coworkers :D


If you want two vectors, you should declare:

 vector<double> testVect[2];

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

And you should enable all warnings on your compiler.

BTW, you could install a recent Linux distribution, with a recent GCC compiler (e.g. 4.7), and run it as g++ -Wall -g it would certainly have warned you if you statically accessed the testVect out of bounds, like it seems that you have had.

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