Vector class in ROOT

Hi all,

I’ve been trying to use vector containers in ROOT, but have come across some issues.

Example:

root.exe

#include;
vector v;
for(int i = 0; i < 5; i++) v.push_back(i);
for(int i = 0; i < 5; i++) cout<<v[i]<<endl;
0
1
2
3
4
for(int i = 0; i < 10; i++) if(v[i] == 2) v.erase(v.begin()+i);
for(int i = 0; i < 5; i++) cout<<v[i]<<endl;
0
1
3
4
4

When I remove an element from the vector v, another element (the last element) gets added to the vector? It seems that the size of the vector does not change.

If I compile this same example with g++, the element is removed and the size of the vector is reduced.

This works with as expected with g++, but not with ROOT.

Thanks,

-Mike

Try again.

typedef vector<int> VecInt_t; for( VecInt_t::size_type i = 0; i < v.size(); ++i) cout<<v[i]<<endl;

or use STD algorithms to avoid such problems of misunderstanding, something like that and any other:

copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n"));

Something to read:
sgi.com/tech/stl/Vector.html
en.wikibooks.org/wiki/More_C%2B% … ase-Remove
gotw.ca/gotw/054.htm
devx.com/tips/Tip/5842

You’re problem is that you are accessing memory that the vector doesn’t control. Your “push_back” loop has put EXACTLY five elements into the vector. So, in this following line,

for(int i = 0; i < 10; i++) if(v[i] == 2) v.erase(v.begin()+i);

you attempt to access (with operator) memory locations about which the vector is not required to know anything. You got lucky that this didn’t result in a program crash. You also got luck that the erase() call removed the element you were expecting it to remove, and didn’t do other horrible things. But then, this line:

for(int i = 0; i < 5; i++) cout<<v[i]<<endl;

also has undefined behavior; the vector now only has four elements, an you attempt to access beyond the end with the call v[4]. Again, this could crash, or do other horrible things. In your case, you once again got lucky.

You should follow the advice of other posters in this thread, and read up on the STL, or at the very least, std::vector<>. There are a number of other problems with your code that Root is letting slide, but which will come back to bite you if you try to compile this code.