473,657 Members | 2,574 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bizarre vector insertion behavior - can someone please enlighten?

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"
#include<vector >

int main(array<Syst em::String ^^args)
{
std::vector<int vectorList;

for (unsigned int i = 0; i < 45; ++i) // works if 45 is
replaced with smaller value.
vectorList.push _back(i);

unsigned int aBegin = 25;
unsigned int aEnd = 35; // works if 35 is replaced with 34.

vectorList.inse rt(vectorList.b egin() + 35, // works if 35 is
replaced by 36, 37, 38 ...
// but not if 35 is replaced by 34, 33, 32...
vectorList.begi n() + aBegin, vectorList.begi n() + aEnd);

return 0;
}

//=============== =========

When this is run, an error occurs during the insertion about
incompatible vector iterators.
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.

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.

Any insight appreciated!

CK

Mar 7 '07 #1
9 6532
ck***********@g mail.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<Syst em::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.inse rt(vectorList.b egin() + 35, // works if 35 is
replaced by 36, 37, 38 ...
// but not if 35 is replaced by 34, 33, 32...
vectorList.begi n() + aBegin, vectorList.begi n() + 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.rese rve(vectorList. size() + how_many_to_ins ert);
>
return 0;
}

//=============== =========

When this is run, an error occurs during the insertion about
incompatible vector iterators.
"incompatib le"? 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
Mar 7 '07 #2
Hi Victor,

Thank you for your tips about posting here. It was my first post to
this newsgroup.

I thought of the reserve possibility, and it doesn't fix the problem.
When the code is run, I get:

Debug Assertion Failed!

Program:...
File: C:\Program Files\Microsoft Visual Studio 8\VC\include\ve ctor
Line: 238

Expression: vector iterators incompatible
I took a look at Stroustrup's examples with fruit (3rd ed., p. 453),
and noticed that he avoids inserting a segment of a vector into
itself. However, Microsoft's own help on vector insert does use an
example of such an insertion. Also Stroustrup does not mention any
concern with self-insertion.

The only way I have of getting around this error that I hope is a
consistent fix is to do the following:

std::vector<int temp;
temp.assign(vec torList.begin() + aBegin, vectorList.begi n() +
aEnd);
vectorList.inse rt(vectorList.b egin() + 35, temp.begin(),
temp.end());

Does the code I posted earlier run without the error on other
compilers? Sorry about the MS-isms.

CK

Mar 7 '07 #3
Victor Bazarov wrote:
ck***********@g mail.com wrote:
[snip}
> 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.inse rt(vectorList.b egin() + 35, // works if 35 is
replaced by 36, 37, 38 ...
// but not if 35 is replaced by 34, 33, 32...
vectorList.begi n() + aBegin, vectorList.begi n() + aEnd);
[snip]
>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.
Actually, that can be phrased more general: never use

a.insert(p,i,j) // p : iterator into the vector
// i,j : iterators

to insert elements of a vector into itself. The precondition for this method
is stated in Table 67 as: pre: i,j are not iterators into a.
Best

Kai-Uwe Bux
Mar 7 '07 #4
Hi,
I'm not sure, but I think the iterator doesn't keep a pointer to
its vector, but a pointer to the vector's data (which is an array).
Now I think, when you insert into the vector and the vector has
to reallocate its data array, the pointer in the iterator becomes
invalid. Maybe it works for values lower than 35, because reallocation
doesn't happen then. But that's just a wild guess.

Regards
Thorsten

Mar 7 '07 #5
ck***********@g mail.com wrote:
[..]
Does the code I posted earlier run without the error on other
compilers? [..]
I am not even going to try. It has undefined behaviour, and
as such can cause nasal demons to take to the air.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 7 '07 #6
Thanks to all for their replies.

It seems that the lesson I have to learn is that an official reference
to the standard template library would be valuable.

Is that what the "Table 67" is from that Kae-Uwe Bux refers to? Could
you please provide the name of the reference source? I googled it and
did find a Table 67 in a gcc.gnu.org website. Is that the source?

CK

Mar 7 '07 #7
ck***********@g mail.com wrote:
Thanks to all for their replies.

It seems that the lesson I have to learn is that an official reference
to the standard template library would be valuable.

Is that what the "Table 67" is from that Kae-Uwe Bux refers to? Could
you please provide the name of the reference source? I googled it and
did find a Table 67 in a gcc.gnu.org website. Is that the source?
The Standard document. Table 67 is titled "Sequence requirements (in
addition to container)". See FAQ or search the archives on how to get
a copy of the Standard.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 7 '07 #8
ck***********@g mail.com writes:
Thanks to all for their replies.

It seems that the lesson I have to learn is that an official reference
to the standard template library would be valuable.
Every C++ programmer should have Josuttis' "The C++ Standard Library"
on their desk, among others.

----------------------------------------------------------------------
Dave Steffen, Ph.D. Disobey this command!
Software Engineer IV - Douglas Hofstadter
Numerica Corporation
dg@steffen a@t numerica d@ot us (remove @'s to email me)
Mar 7 '07 #9
ck***********@g mail.com wrote:
Thanks to all for their replies.

It seems that the lesson I have to learn is that an official reference
to the standard template library would be valuable.

Is that what the "Table 67" is from that Kae-Uwe Bux refers to? Could
you please provide the name of the reference source? I googled it and
did find a Table 67 in a gcc.gnu.org website. Is that the source?

CK
Not "official", but this is a quite good reference:
http://www.sgi.com/tech/stl/table_of_contents.html

--
Alan Johnson
Mar 8 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3136
by: Mattias Brändström | last post by:
Hello all! I am trying to write code that allows me to initialise one of my classes inline (with a vector like structure). Inline might not be the best term to use here but I can't think of any other right now. Here is my code: template <typename T> class Array { public: Array& operator()(const T& v) {
34
4163
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and "push_back" a copy of this into a vector V. This is repeated many times in an iterative process. Ok whenever I "push_back" a copy of Class A, I also want to assign a pointer contained in an exisiting instance of a Class B to this
9
5197
by: Amadeus W. M. | last post by:
I have a vector from which I want to erase elements between iterators i,j. If i<j, everything works as expected, but if j>i, an insertion is actually performed. Example: vector<double> x(10); vector<double>::iterator i=x.begin()+2, j=x.begin()+6; x.erase(i,j); // i<j, ok, erases 4 elements. x.erase(j,i); // j>i, no error, just inserts 4 elements.
13
20126
by: zaineb | last post by:
Hi, This is a follow-up of sort of this thread: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/de12af6539e0d645/662cab752779f1fa?lnk=st&q=c%2B%2B+vector+vs+map&rnum=1&hl=en#662cab752779f1fa I've been chewing on this problem for a while. When I came across the above thread, I figured that maybe other members have a better idea on how to approach this. I'm currently trying to decide between which one of maps or...
28
1938
by: VK | last post by:
A while ago I wrote a "Vector data type" script using DOM interface to select.options. That was a (beautiful) mind game :-) rather than a practical thing to use. Here is another attempt open for criticism, this time dead serious. I really need an effective Vector emulator for a project (as much effective as something not implemeted in language but emulated by means of the language itself is: a
0
371
by: ckfan.painter | last post by:
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.
12
4908
by: desktop | last post by:
Why does insert only work when specifying an iterator plus the object to be inserted: std::vector<intt; std::vector<int>::iterator it; it = t.begin(); t.insert(it,33); If I use push_back instead I don't need to supply the iterator. But what
4
1613
by: er | last post by:
hi, the code below generates the following behavior. cld someone please help understand it? 1) clean project + build project generates build errors (see bottom) 2) build a second time, errors disappears, run: ok 3) uncomment and comment , no problem 4) uncomment and , also no problem #ifndef A_IMPL_H_
1
2535
by: subramanian100in | last post by:
Suppose I have vector<intvi; deque<intdi; list<intli; Suppose all of these containers have some elements. Suppose 'v_iter' is an iterator pointing to some element in 'vi'. Suppose 'v_beg' and 'v_end' are valid iterators pointing to some
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8823
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8730
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7321
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1950
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.