473,663 Members | 2,726 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Erasing map elements by iterator

Hi,

Is the following code legal? g++ 3.2 barfs on it, although it seems
fine to me.

#include <map>

using std::map;

int main()
{
map<int,int> i;
i[0]=6;
i[54]=2;
map<int,int>::i terator it=i.begin();
while(it!=i.end ())
{
if(it->first==0) it=i.erase(it);
else it++;
}
return 0;

}

The error message from g++ is:
tmp.cpp:13: no match for `std::_Rb_tree_ iterator<std::p air<const int,
int>,
std::pair<const int, int>&, std::pair<const int, int>*>& = void'
operator
/usr/include/c++/3.2/bits/stl_tree.h:184: candidates are:
std::_Rb_tree_i terator<std::pa ir<const int, int>, std::pair<const
int,
int>&, std::pair<const int, int>*>&
std::_Rb_tree_i terator<std::pa ir<const
int, int>, std::pair<const int, int>&, std::pair<const int,
int>*>::operato r=(const std::_Rb_tree_i terator<std::pa ir<const int,
int>,
std::pair<const int, int>&, std::pair<const int, int>*>&)
As a workaround, is it valid to do the following, or does erasing the
iterator 'tmp' from the map (below) render the iterator 'it' invalid?
#include <map>

using std::map;

int main()
{
map<int,int> i;
i[0]=6;
i[54]=2;
map<int,int>::i terator it=i.begin();
while(it!=i.end ())
{
if(it->first==0)
{
map<int,int>::i terator tmp=it;
it++;
i.erase(tmp);
}
else it++;
}
return 0;

}

Regards,

Owen Brydon
Jul 19 '05 #1
5 10185

"Owen Brydon" <ow*********@st .com> wrote in message news:63******** *************** ***@posting.goo gle.com...
Is the following code legal? g++ 3.2 barfs on it, although it seems
fine to me.
It's not.
if(it->first==0) it=i.erase(it);


map::erase returns void.

if(it->first == 0) it.erase(it++);
else ++it;

Jul 19 '05 #2
Owen Brydon wrote:
Hi,

Is the following code legal? g++ 3.2 barfs on it, although it seems
fine to me.

#include <map>

using std::map;

int main()
{
map<int,int> i;
i[0]=6;
i[54]=2;
map<int,int>::i terator it=i.begin();
while(it!=i.end ())
{
if(it->first==0) it=i.erase(it); map::erase returns void
else it++;
}
return 0;

}

The error message from g++ is:
tmp.cpp:13: no match for `std::_Rb_tree_ iterator<std::p air<const int,
int>,
std::pair<const int, int>&, std::pair<const int, int>*>& = void'
operator
gcc complains it can't find a void assignment ....

As a workaround, is it valid to do the following, or does erasing the
iterator 'tmp' from the map (below) render the iterator 'it' invalid?


The code is fine and likely the only way to do it. A map iterator
remains valid for the life of the map entry.

Jul 19 '05 #3
Ron Natalie wrote:
"Owen Brydon" <ow*********@st .com> wrote in message
news:63******** *************** ***@posting.goo gle.com...

Is the following code legal? g++ 3.2 barfs on it, although it seems
fine to me.

It's not.
if(it->first==0) it=i.erase(it);

It seems not :)
In this case,
http://www.dinkumware.com/manuals/re...=p/&h=map.html is
incorrect, which is where I got the notion that it returned an iterator.

map::erase returns void.

if(it->first == 0) it.erase(it++); else ++it;


Is this 100% safe? Is the iterator it valid for postincrement after
being erased from the map?

Is the other example I gave where the iterator is copied, then
incremented, then the copy is erased, 100% safe?

Regards,

Owen Brydon

Jul 19 '05 #4
On Wed, 15 Oct 2003 18:52:30 +0100, Owen Brydon <ow**@dsl.pipex .com> wrote:
Ron Natalie wrote:
"Owen Brydon" <ow*********@st .com> wrote in message
news:63******** *************** ***@posting.goo gle.com...

Is the following code legal? g++ 3.2 barfs on it, although it seems
fine to me.

It's not.
if(it->first==0) it=i.erase(it);

It seems not :)
In this case,
http://www.dinkumware.com/manuals/re...=p/&h=map.html is
incorrect, which is where I got the notion that it returned an iterator.


map erase(const key_type&) returns size_type

map::erase returns void.

if(it->first == 0) it.erase(it++); else ++it;

Is this 100% safe? Is the iterator it valid for postincrement after being
erased from the map?


erase has an iterator argument, postincrement operator ++ applied to map
iterator returns copy of current iterator and increments current iterator.

Is the other example I gave where the iterator is copied, then
incremented, then the copy is erased, 100% safe?
Yes,it is, as well as the shorter version above which does the same.

Regards,

Owen Brydon


--
grzegorz
Jul 19 '05 #5
>> map::erase returns void.
if(it->first == 0) it.erase(it++); else ++it;


Owen> Is this 100% safe? Is the iterator it valid for postincrement after
Owen> being erased from the map?

The example has a typographical error: it.erase(it++) should be
i.erase(it++). With that change, the example is 100% safe:
Although it skates right up to the edge of the broken ice, it
avoids drowning in the frigid water.

The key is that there is a sequence point between evaluating a
function's arguments and calling the function, which means that
before i.erase is called, the value of it has already been
incremented. Therefore, it is no longer referring to the element
that is about to be deleted, and its value therefore remains valid.

--
Andrew Koenig, ar*@acm.org
Jul 19 '05 #6

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

Similar topics

8
2202
by: Generic Usenet Account | last post by:
To settle the dispute regarding what happens when an "erase" method is invoked on an STL container (i.e. whether the element is merely removed from the container or whether it also gets deleted in the process), I looked up the STL code. Erase certainly does not delete the memory associated with the element. However, it appears that the destructor on the element is invoked. I wonder why it has to be this way. In my opinion, this renders...
12
2320
by: Tescobar | last post by:
Over one year ago somebody asked here: how to remove selected elements from list in a loop?. The answer was as follows: for( it = l.begin(); it != l.end; ) { if(...) it = l.erase(it); else ++it;
3
1593
by: KK | last post by:
Hello comp.lang.c++, Is it possible to construct an iterator for a class that can traverse through all the elements associated with that class? Class AnotherDataType; //defined somewhere else Class Crazy { int _num; std::string _name; unsinged int _index; AnotherDataType _tmp;
11
4351
by: eeykay | last post by:
Hello, I am facing a starnge problem while erasing the last member in a vector. I am using VC++ .NET 2002 complier. I have vector of CComPtr<..> (irrelevant here), and then I iterate over the vector. If it is the iterator, then I remove the element from the vector using vecObjects.erase(it). It works fine till the last element. While removing the last element it throws exception and fails. But the same vecObject.clear() works with out...
5
12057
by: ma740988 | last post by:
For starters, Happy New Year to all!! I created a vector of pairs where pair first is a primitive and pair second is a vector of ints. So now: # include <iostream> # include <vector>
7
6594
by: linq936 | last post by:
Hi, The following is a psudo code to describe my question: vector<int> ints; vector<int>::iterator itr; while (itr != ints.end()){ int j = some_function(*i); if (j>0){ ints.push_back(j); }
10
6059
by: arnuld | last post by:
WANTED: /* C++ Primer - 4/e * * Exercise: 9.26 * STATEMENT * Using the following definition of ia, copy ia into a vector and into a list. Use the single iterator form of erase to remove the elements with odd values from your list * and the even values from your vector.
1
1726
by: Henrik Goldman | last post by:
Hello, I would like to know if it's legal to insert one or more items into a std::map while traversing it from begin() to end(). E.g. for (it = mymap.begin(); it != mymap.end(); it++) { if (condition)
3
2933
by: Angus | last post by:
If I want to erase all list items with a value of say 3 as below: std::list<intmylist; mylist.push_back(3); mylist.push_back(4); mylist.push_back(5); mylist.push_back(6); for(std::list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it) {
0
8345
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
8858
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...
1
8548
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7371
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
6186
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
4182
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4349
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2763
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
2
1757
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.