Re: Bizarre vector insertion behavior - can someone please enlighten?
ckfan.painter@gmail.com wrote:
I've run into a seemingly bizarre problem with insert() for
std::vector. (This was done on Microsoft Visual C++ 2005 express
version 8...maybe it is a compiler specific bug?)
Here's the code:
//===================
// vector tester 3.cpp : main project file.
#include "stdafx.h"
You might want to consider weeding MS-isms out before posting here.
#include<vector>
int main(array<System::String ^> ^args)
That's not Standard C++, sorry. For managed extensions, try MS
newsgroups.
{
std::vector<int> vectorList;
for (unsigned int i = 0; i < 45; ++i) // works if 45 is
replaced with smaller value.
What "works"? By extension, what "doesn't"?
vectorList.push_back(i);
unsigned int aBegin = 25;
unsigned int aEnd = 35; // works if 35 is replaced with 34.
vectorList.insert(vectorList.begin() + 35, // works if 35 is
replaced by 36, 37, 38 ...
// but not if 35 is replaced by 34, 33, 32...
vectorList.begin() + aBegin, vectorList.begin() + aEnd);
Any insertion into the middle of the vector can invalidate _all_
of its iterators (the one returned by 'begin()' included). Your
program most likely has undefined behaviour.
You can avoid that if you reserve memory in the vector:
vectorList.reserve(vectorList.size() + how_many_to_insert);
return 0;
}
//========================
When this is run, an error occurs during the insertion about
incompatible vector iterators.
"incompatible"? I don't think this is a Standard term.
At first I thought, maybe this is happening because I'm trying to
insert into the range that I am copying...but, if the size of the
vector is just changed from 45 elements long to 44 elements long...the
program works! I think that is just bizarre.
It isn't. See above.
Does anybody understand what is going on here? It would be crazy to
write code that might fail whenever it encounters a vector.insert() so
I would like to understand the reason this code fails but when the 45
is replaced with 44, it works.
Do not insert the elements of a vector into itself without reserving
first.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask