Saturday, August 4, 2007

STL Vector in VS 2005 ( when porting from 2003 or < )

In VS 2005 they changed almost all C runtime libraries and STL classes for adding security practices. Here is one information about the vector class in STL. So if you have any code written in 2003 , and if you port that to VS2005 be careful. 

In 2003 the following vector operations will work , like
vector<int> SomeInts;
SomeInte.push_back(0);
SomeInte.push_back(1);
SomeInte.push_back(2);


vector<int>::iterator it = SomeInts.Begin(); // Now it points to 0
++it;                                       // Now it points to 1
SomeInts.erase(it);                         // We are deleting the 1 from list
--it                                        // We want to move to 0 again.


and if you again ++it you will get 2. because we just deleted 1 from the vector. Ok, everything fine.
But In VS 2005 , the red marked line above(--it) cause to a crash!!! Open-mouthed. Because the iterator it is invalid so --it is also invalid.

 SO to correct that error best way is like this

vector<int> SomeInts;
SomeInte.push_back(0);
SomeInte.push_back(1);
SomeInte.push_back(2);
vector<int>::iterator it = SomeInts.Begin();   // Now it points to 0
++it;                                          // Now it points to 1
it = SomeInts.erase(it);                       // We are deleting the 1 from list
--it                                           // Now it points to 0


[ The last day , my friend told me he is getting a strange error in VS2005 , not in 2003, it was this problem. Smile]

No comments: