Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Vectors C++ - curious behaviour when adding elements

Tags:

c++

arrays

vector

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

testVect[0].push_back(0);

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

like image 942
Andrey Lujankin Avatar asked Dec 05 '12 17:12

Andrey Lujankin


People also ask

Is it better to use array or vector?

Vector is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure.

Which is faster vector or array C++?

The conclusion is that arrays of integers are faster than vectors of integers (5 times in my example). However, arrays and vectors are arround the same speed for more complex / not aligned data.


1 Answers

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.

like image 179
Basile Starynkevitch Avatar answered Oct 20 '22 00:10

Basile Starynkevitch