473,651 Members | 2,531 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Strange behaviors of Iterator for set

Hi,
Today, I make some test on the C++ STL iterators of set containers
with GNU g++ compiler. The code is:

#include <set>
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
set<intms;
int i;
for (i=1; i<10; i++)
ms.insert(i);

set<int>::itera tor it = ms.begin();
it++;

ms.erase(it);
cout << "Deleted: " << *(it) << endl;
set<int>::itera tor ii = it;
cout << "++: " << *(++ii) << endl;
cout << "+2: " << *(++ii) << endl;
cout << "--: " << *(--it) << endl;
it++;
cout << "--++: " << *(it) << endl;

ms.insert(2);
it = ms.begin();
it++;
it++;
it++;
it++;

ms.erase(it);
cout << "Deleted: " << *(it) << endl;
ii = it;
cout << "++: " << *(++ii) << endl;
cout << "+2: " << *(++ii) << endl;
cout << "--: " << *(--it) << endl;
it++;
cout << "--++: " << *(it) << endl;

it = ms.end();
it--;
ms.erase(it);
cout << "Deelted: " << *(it) << endl;
cout << "++: " << *(++it) << endl;
cout << "+2: " << *(++it) << endl;

return 0;
}

and the output is:
Deleted: 2
++: 1
+2: 3
--: 1
--++: 3
Deleted: 5
++: 6
+2: 7
--: 6
--++: 7
Deelted: 9
++: 8
+2: 7

I find that, when I erase something, the whole iterator's behavior is
unpredicted. I can't make sure what is a next ++ is in a set unlike I
am sure with a vector...
Does this a right behaviors? And when I use the remove_if and many
other algorithm on set, it will make some crash, why?

Thanks a lot!

Regards!
Bo
Nov 19 '08 #1
8 1909
Bo Yang wrote:
Hi,
Today, I make some test on the C++ STL iterators of set containers
with GNU g++ compiler. The code is:

#include <set>
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
set<intms;
int i;
for (i=1; i<10; i++)
ms.insert(i);

set<int>::itera tor it = ms.begin();
it++;

ms.erase(it);
cout << "Deleted: " << *(it) << endl;
Undefined behaviour. You're trying to dereference an invalid
iterator.
set<int>::itera tor ii = it;
You're constructing another iterator and initialising it from
the invalid iterator; the 'ii' becomes invalid immediately.
cout << "++: " << *(++ii) << endl;
cout << "+2: " << *(++ii) << endl;
cout << "--: " << *(--it) << endl;
it++;
cout << "--++: " << *(it) << endl;
All this is undefined behaviour, by itself and due to the
preceding undefined behaviour.
>
ms.insert(2);
it = ms.begin();
it++;
it++;
it++;
it++;
This is all fine. 'it' is valid still, because your set
contains more than 4 values.
ms.erase(it);
cout << "Deleted: " << *(it) << endl;
ii = it;
cout << "++: " << *(++ii) << endl;
cout << "+2: " << *(++ii) << endl;
cout << "--: " << *(--it) << endl;
it++;
cout << "--++: " << *(it) << endl;
Here you go again...
>
it = ms.end();
it--;
That's fine. 'it' refers to the last element in the set.
ms.erase(it);
'it' now is invalid.
cout << "Deelted: " << *(it) << endl;
cout << "++: " << *(++it) << endl;
cout << "+2: " << *(++it) << endl;
And again, you're using an invalid iterator. Undefined
behaviour.
>
return 0;
}

and the output is:
Deleted: 2
++: 1
+2: 3
--: 1
--++: 3
Deleted: 5
++: 6
+2: 7
--: 6
--++: 7
Deelted: 9
++: 8
+2: 7

I find that, when I erase something, the whole iterator's behavior is
unpredicted.
Of course. When you erase the element through an iterator, the
iterator becomes *invalid*. It has no behavior defined by the
language.
I can't make sure what is a next ++ is in a set unlike I
am sure with a vector...
I don't understand that sentence. With all standard containers
if you erase the object, the iterator that used to refer to the
deleted object becomes *invalid*. What ++, what vector?
Does this a right behaviors?
Yes, it does, I guess.
And when I use the remove_if and many
other algorithm on set, it will make some crash, why?
Don't know. Show the code, then we can talk.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 19 '08 #2
What'z up Bo?
Nov 19 '08 #3
James Kanze wrote:
On Nov 19, 3:35 am, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
>Bo Yang wrote:

[...]
>>And when I use the remove_if and many other algorithm on
set, it will make some crash, why?
>Don't know. Show the code, then we can talk.

It shouldn't compile, if your library implementation and
compiler are conformant. You can't modify members of a set,
which means that none of the mutating algorithms can be used on
it. remove_if is a mutating algorithm.
It's mutating to the sequence, not to the elements. Removing from a set
is well-defined and it keeps the set in stable state, doesn't it?
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 19 '08 #4
On 2008-11-19 09:22:25 -0500, Victor Bazarov <v.********@com Acast.netsaid:
James Kanze wrote:
>On Nov 19, 3:35 am, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
>>Bo Yang wrote:

[...]
>>>And when I use the remove_if and many other algorithm on
set, it will make some crash, why?
>>Don't know. Show the code, then we can talk.

It shouldn't compile, if your library implementation and
compiler are conformant. You can't modify members of a set,
which means that none of the mutating algorithms can be used on
it. remove_if is a mutating algorithm.

It's mutating to the sequence, not to the elements. Removing from a
set is well-defined and it keeps the set in stable state, doesn't it?
remove_if, like all the standalone algorithms, operates on the elements
of a sequence and not on the underlying data structure. That's the
essential abstraction that iterators present. Think of how remove_if
would work on a vector: copy elements downward, but don't copy elements
that should be removed.

The key thing here is that algorithms operate on sequences, not on
containers. Containers are a way of producing sequences, but algorithms
don't know where the sequence came from, so cannot apply operations
like removing an element from a set. And that's why list has its own
sort member function: the generic sort algorithm doesn't work for a
list, so you need a container-specific sort function.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Nov 19 '08 #5
On Nov 20, 12:25*am, Pete Becker <p...@versatile coding.comwrote :
On 2008-11-19 09:22:25 -0500, Victor Bazarov <v.Abaza...@com Acast.netsaid:
James Kanze wrote:
On Nov 19, 3:35 am, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
Bo Yang wrote:
* * [...]
And when I use the remove_if and many other algorithm on
set, it will make some crash, why?
>Don't know. *Show the code, then we can talk.
It shouldn't compile, if your library implementation and
compiler are conformant. *You can't modify members of a set,
which means that none of the mutating algorithms can be used on
it. *remove_if is a mutating algorithm.
It's mutating to the sequence, not to the elements. *Removing from a
set is well-defined and it keeps the set in stable state, doesn't it?

remove_if, like all the standalone algorithms, operates on the elements
of a sequence and not on the underlying data structure. That's the
essential abstraction that iterators present. Think of how remove_if
would work on a vector: copy elements downward, but don't copy elements
that should be removed.

The key thing here is that algorithms operate on sequences, not on
containers. Containers are a way of producing sequences, but algorithms
don't know where the sequence came from, so cannot apply operations
like removing an element from a set. And that's why list has its own
sort member function: the generic sort algorithm doesn't work for a
list, so you need a container-specific sort function.
Ah, that is a good point. If STL algorithms operate on sequences, I
understand why my program failing. Thanks!

Regards!
Bo
Nov 20 '08 #6
On Nov 19, 3:22 pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
James Kanze wrote:
On Nov 19, 3:35 am, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
Bo Yang wrote:
[...]
>And when I use the remove_if and many other algorithm on
set, it will make some crash, why?
Don't know. Show the code, then we can talk.
It shouldn't compile, if your library implementation and
compiler are conformant. You can't modify members of a set,
which means that none of the mutating algorithms can be used
on it. remove_if is a mutating algorithm.
It's mutating to the sequence, not to the elements. Removing
from a set is well-defined and it keeps the set in stable
state, doesn't it?
Removing elements from a set is well defined, but the standard
library changes the meanings of some common English words, so
remove (and remove_if) don't mean remove (which is spelled erase
in the standard), but reorder. And any attempt to reorder a set
is going to cause problems somewhere, because in the standard,
set doesn't mean set, but is a list ordered on some specified
criterion.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Nov 20 '08 #7
On Nov 20, 2:25 am, Bo Yang <struggl...@gma il.comwrote:
On Nov 19, 5:24 pm, James Kanze <james.ka...@gm ail.comwrote:
On Nov 19, 3:35 am, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
[...]
Do you mean all associative containers such as
set/multiset/map/ multimap can't be dealt with mutating
algorithms?
No. It is only the key_type which can't be mutated. In set and
multiset, the key_type is the entire element, but in map and
multimap, it's only part of the element. (Internally, the
associative containers maintain their elements ordered on the
key_type; if you mutate the key_type, you can violate the
invariants maintaining the ordering.)

Of course, remove_if reassigns the entire element, so it can't
be used on any of the associative containers. (From a quick
glance, I think that this is true for all of the mutating
algorithms. But you could write an algorithm of your own for
std::map which only mutated the mapped_type.)
And that is to say that only vector/list/deque can be applied
by this algorithm?
Or any container of your own which allows mutation of a complete
element through an iterator.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 20 '08 #8
On 2008-11-20 03:50:41 -0500, James Kanze <ja*********@gm ail.comsaid:
>
Removing elements from a set is well defined, but the standard
library changes the meanings of some common English words, so
remove (and remove_if) don't mean remove (which is spelled erase
in the standard), but reorder.
This muddles the fundamental distinction between sequences and
containers. The global algorithm remove_if operates on sequences. erase
operates on containers. Containers are a way to manage sequences, but
they are not sequences.
And any attempt to reorder a set
is going to cause problems somewhere, because in the standard,
set doesn't mean set, but is a list ordered on some specified
criterion.
remove_if doesn't reorder. It removes elements. If you call remove_if
to remove 2's from the input sequence

1 2 3 2 4 5 2 6

the result, designated by the start iterator of the original input
sequence and the end iterator returned by remove_if, is the sequence

1 3 4 5 6

If you got the input sequence by calling begin() and end() on a
vector<intyou can look at the elements of the vector that come after
the result sequence (i.e. the elements beginning at the iterator that
remove_if returned), and you'll see whatever junk was left over. If you
want to have the vector hold the result sequence you have to erase
those junk elements, because the algorithm can't. But now you're
dealing with the vector that manages the sequence, and not with the
sequence itself.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Nov 20 '08 #9

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

Similar topics

5
1568
by: RCS | last post by:
I have this Functor: typedef std::vector < std::string > String_vec; typedef std::vector < String_vec > StrVec_vec; class Compare : public std::unary_function<String_vec, void> { public: StrVec_vec myData;
2
2402
by: Dave | last post by:
I'm crossposting this to both comp.lang.c++ and gnu.gcc because I'm not sure if this is correct behavior or not, and I'm using the gcc STL and compiler. When calling vector<int>::push_back(0), an iterator that I've set in a loop gets changed. Here's an example of the problem (sorry about the lack of indentation, posting this from Google): #include <vector> #include <iostream>
0
1054
by: Lieven | last post by:
Hey, I'm developing a medical application. Medical data is presented in xml files. I have to queries these xml files to retrieve some data, for example the birthday of the patient. This is possible with this code: XPathDocument Doc = new XPathDocument("115160760042149.xml"); XPathNavigator navigator = Doc.CreateNavigator(); XPathNodeIterator iterator =
5
1682
by: cody | last post by:
I have a very funny/strange effect here. if I let the delegate do "return prop.GetGetMethod().Invoke(info.AudioHeader, null);" then I get wrong results, that is, a wrong method is called and I have no clue why. But if I store the MethodInfo in a local variable I works as expected. I do not understand why this is so, shouldn't both ways be semantically equal?
6
1693
by: Gary | last post by:
I have an application that has been working just fine for a couple of years. It queries a SQL database and returns some formatted data back to the client. I have a new client, who has a larger database than any of our previous customers. For example, the query to build the datatable now takes about 2 minutes instead of one minute or less. This is a third party database we are integrating with. He is getting very strange results. For...
3
1825
by: Shelly | last post by:
I am encountering two strange problems. First one: I get a "server misconfiguration error", but only sometimes. It occurs on the first screen that accesses the database on a submit. This error is intermittent -- sometimes it happens and sometimes not from the same screen with the same data. Here is the error:
12
2262
by: StephQ | last post by:
I have a class Bounds with two constructors: class Bounds { private: list<SegmentupperLinearSpline; // Upper bound. list<SegmentlowerLinearSpline; // Lower bound. ....
0
1528
by: adamalton | last post by:
I'm trying to investigate the way PHP behaves in relation to timeouts and included scripts. PHP seems to do very strange things when scripts that include other scripts timeout, or when the included scripts themselves timeout. Just wondering if anyone else has ever investigated this world of mystery, or if they would like to join me in my quest into the unknown!!....?? It appears that in some cases php will return a completely balnk page...
6
1475
by: Michael Coley | last post by:
Hi, I've wrote this function which should add a comma for every 3 digits in a number (so that it looks something like 5,000). This is my function: std::string formatNumber(int number) { // Convert the int to a string. std::string numString = boost::lexical_cast<std::string>(number); std::string::const_reverse_iterator i = numString.rbegin(), end =
0
8347
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
8792
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
8694
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
8571
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6157
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
5605
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
4280
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2696
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1905
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.