473,385 Members | 1,707 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Fast Erase on Map

Hi,

I know if you call erase when you iterate through map you will crash.
Ex:

map<int,doublem;
// insert something
for ( map<int, double>::iterator i = m.begin(); i != m.end(); i++ )
if ( i->second < 0 ) m.erase(i);

This will crash because erase() will corrupt iterator. Now what I do I
insert key into list and erase each key. After first loop. Is there way
to do this erase in the same search loop?

Aug 16 '06 #1
11 5509

mo********@yahoo.com wrote:
Hi,

I know if you call erase when you iterate through map you will crash.
Ex:

map<int,doublem;
// insert something
for ( map<int, double>::iterator i = m.begin(); i != m.end(); i++ )
if ( i->second < 0 ) m.erase(i);

This will crash because erase() will corrupt iterator. Now what I do I
insert key into list and erase each key. After first loop. Is there way
to do this erase in the same search loop?
Do not increment the iterator after an erase - this is undefined.

for ( map<int, double>::iterator i = m.begin(); i != m.end(); /* NO
INCREMENT */ )
if ( i->second < 0 ) i = m.erase(i);
else
++i;
/Peter

Aug 16 '06 #2
peter koch wrote:
mo********@yahoo.com wrote:
>Hi,

I know if you call erase when you iterate through map you will crash.
Ex:

map<int,doublem;
// insert something
for ( map<int, double>::iterator i = m.begin(); i != m.end(); i++ )
if ( i->second < 0 ) m.erase(i);

This will crash because erase() will corrupt iterator. Now what I do
I insert key into list and erase each key. After first loop. Is
there way to do this erase in the same search loop?

Do not increment the iterator after an erase - this is undefined.

for ( map<int, double>::iterator i = m.begin(); i != m.end(); /* NO
INCREMENT */ )
if ( i->second < 0 ) i = m.erase(i);
else
++i;
std::map::erase does NOT return an iterator (yet). Many current SL
implementations may actually have that, but it shouldn't be relied
upon. The idiom is to increment as part of the call to erase:

if (i->second < 0) m.erase(i++);
else ++i;
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 16 '06 #3
Hello,

mo********@yahoo.com wrote:
map<int,doublem;
// insert something
for ( map<int, double>::iterator i = m.begin(); i != m.end(); i++ )
if ( i->second < 0 ) m.erase(i);
You have to increment before erase, e.g.

for ( map<int, double>::iterator i = m.begin(); i != m.end(); ) {
map<int, double>::iterator j = i++;
if ( j->second < 0 ) m.erase(j);
}

Bernd Strieder

Aug 16 '06 #4
In article <11**********************@m79g2000cwm.googlegroups .com>,
mo********@yahoo.com says...
Hi,

I know if you call erase when you iterate through map you will crash.
Ex:

map<int,doublem;
// insert something
for ( map<int, double>::iterator i = m.begin(); i != m.end(); i++ )
if ( i->second < 0 ) m.erase(i);

This will crash because erase() will corrupt iterator. Now what I do I
insert key into list and erase each key. After first loop. Is there way
to do this erase in the same search loop?
I'm not sure I have straight what you're trying to accomplish.

From your code it looks like you want to copy only a subset of the items
from the map into a list and erase only those items from the map (I.e.
basically move each qualifying item from the map to the list).

If that's the case, then most of what you have is reasonable. The main
change you need is to use the return value from m.erase(). erase()
returns an iterator to the next item after the one you just erased, so
your loop could look something like:

i = m.begin();
while (i!=m.end())
if (i->second < 0) {
// your_list.push_back(*i);
i = m.erase(i);
}
else
++i;

OTOH, your description sounds like you're trying to copy all the
elements from a map into a list, and then basically destroy the map. If
that's the case, you're probably better off with something like:

std::copy(your_map.begin(), your_map.end(),
std::back_inserter(your_list));
your_map.clear();

If you remove the items from the map individually, it'll re-balance the
tree as your removals change the balance. Since you're removing all the
items, the time spent re-balancing the tree is wasted. clear() knows
it's going to produce an empty tree, so it can avoid re-balancing as it
removes nodes.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 16 '06 #5
In article <eb**********@news.datemas.de>, v.********@comAcast.net
says...

[ ... ]
std::map::erase does NOT return an iterator (yet). Many current SL
implementations may actually have that, but it shouldn't be relied
upon. The idiom is to increment as part of the call to erase:

if (i->second < 0) m.erase(i++);
else ++i;
Oops -- Victor is right. My earlier post should be ignored.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 16 '06 #6

Victor Bazarov wrote:
peter koch wrote:
mo********@yahoo.com wrote:
Hi,

I know if you call erase when you iterate through map you will crash.
Ex:

map<int,doublem;
// insert something
for ( map<int, double>::iterator i = m.begin(); i != m.end(); i++ )
if ( i->second < 0 ) m.erase(i);

This will crash because erase() will corrupt iterator. Now what I do
I insert key into list and erase each key. After first loop. Is
there way to do this erase in the same search loop?
Do not increment the iterator after an erase - this is undefined.

for ( map<int, double>::iterator i = m.begin(); i != m.end(); /* NO
INCREMENT */ )
if ( i->second < 0 ) i = m.erase(i);
else
++i;

std::map::erase does NOT return an iterator (yet). Many current SL
implementations may actually have that, but it shouldn't be relied
upon. The idiom is to increment as part of the call to erase:

if (i->second < 0) m.erase(i++);
else ++i;
Hi Victor

Thanks for the information. Actually, I believe I knew that:
unfortunately i just happened to unlearn it again.

/Peter

Aug 16 '06 #7
Victor Bazarov <v.********@comAcast.netwrote:
> if ( i->second < 0 ) i = m.erase(i);
else
++i;

std::map::erase does NOT return an iterator (yet). Many current SL
implementations may actually have that, but it shouldn't be relied
upon. The idiom is to increment as part of the call to erase:

if (i->second < 0) m.erase(i++);
indeed, but above will result in UB if called on vector or deque (eg.
because someone nicely refactored std::map to typedef and then changed
type of the container). Thus I opt for using nonstandard but safe
extension instead, cited on top of this message
B.
--
Remove -trap- when replying. Usun -trap- gdy odpisujesz.

Aug 16 '06 #8

Victor Bazarov wrote:
std::map::erase does NOT return an iterator (yet). Many current SL
implementations may actually have that, but it shouldn't be relied
upon. The idiom is to increment as part of the call to erase:

if (i->second < 0) m.erase(i++);
else ++i;
Ok, thanks. This work. But I am sorry to ask something stupid. I dont
know why it works?? IMHO m.erase(i++) is almost as if you said
m.erase(i); ++i; But your way works, so they must not be the same..
Sorry if I the only one who does not get it, but more explanation would
be good for me. Thank you.

Aug 16 '06 #9

mo********@yahoo.com wrote:
Victor Bazarov wrote:
std::map::erase does NOT return an iterator (yet). Many current SL
implementations may actually have that, but it shouldn't be relied
upon. The idiom is to increment as part of the call to erase:

if (i->second < 0) m.erase(i++);
else ++i;
I think I know why this work. operator ++(int) for iterator does little
trick:
iterator operator++(int)
{ // postincrement
iterator _Tmp = *this;
++*this;
return (_Tmp);
}
It returns copy of itself "before" increment and return by value, not
reference. Is this correct? So maybe I should use ++i (preincrement)
always unless need postincrement because i++ is doing too much. Is it
true?

Aug 16 '06 #10
mo********@yahoo.com a écrit :
mo********@yahoo.com wrote:
>Victor Bazarov wrote:
>>std::map::erase does NOT return an iterator (yet). Many current SL
implementations may actually have that, but it shouldn't be relied
upon. The idiom is to increment as part of the call to erase:

if (i->second < 0) m.erase(i++);
else ++i;
I think I know why this work. operator ++(int) for iterator does little
trick:
iterator operator++(int)
{ // postincrement
iterator _Tmp = *this;
++*this;
return (_Tmp);
}
It returns copy of itself "before" increment and return by value, not
reference. Is this correct? So maybe I should use ++i (preincrement)
always unless need postincrement because i++ is doing too much. Is it
true?
Yes, it is true, but it is not a *little trick*, it is mandatory to get
the semantic of the postfix ++ operator.
Aug 16 '06 #11

mo********@yahoo.com wrote:
mo********@yahoo.com wrote:
Victor Bazarov wrote:
std::map::erase does NOT return an iterator (yet). Many current SL
implementations may actually have that, but it shouldn't be relied
upon. The idiom is to increment as part of the call to erase:
>
if (i->second < 0) m.erase(i++);
else ++i;
>
I think I know why this work. operator ++(int) for iterator does little
trick:
iterator operator++(int)
{ // postincrement
iterator _Tmp = *this;
++*this;
return (_Tmp);
}
It returns copy of itself "before" increment and return by value, not
reference. Is this correct? So maybe I should use ++i (preincrement)
always unless need postincrement because i++ is doing too much. Is it
true?
This is in this group's FAQ:
http://www.parashift.com/c++-faq-lit...html#faq-13.15

--
Alan Johnson

Aug 16 '06 #12

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

Similar topics

5
by: Angus Leeming | last post by:
Dinkumware's online STL reference http://tinyurl.com/3es52 declares std::map's overloaded erase member functions to have the interface: map::erase iterator erase(iterator where); iterator...
7
by: jose luis fernandez diaz | last post by:
Hi, Is this right any stl container (vector, deque, list, . . .)? typedef vector container; int main() { container<int> c1;
3
by: jose luis fernandez diaz | last post by:
Hi, Erase elements while iterating on a map don't invalidate the iterator except the erased one, so the program below: (1) #include <map> int main()
6
by: isaacyho | last post by:
Is there a fast way to crop a vector? I have a vector of size n, and want to reduce it to some subregion (x,y ). Seems like you shouldn't have to recopy all of those elements into a new vector,...
20
by: Tom van Stiphout | last post by:
I'm about to write a function like below, which I'm going to call a lot of times. So I care about possible memory leaks. I think whether I should use Erase or not depends on whether Split creates...
8
by: olanglois | last post by:
Hi, I was asking myself to following question. What is better to erase an element from a STL map: calling (option #1) size_type erase(const key_type& k) or calling (option #2)
6
by: catphive.lists | last post by:
Is there a way to call erase(iter) on a list without invalidating the iterator? Can I make a copy of an iterator and then move forward the original without moving the copy? I'm aware of the...
19
by: Juha Nieminen | last post by:
If I'm not completely mistaken, the only reason why std::list::size() may be (and usually is) a linear-time operation is because they want std::list::splice() to be a constant-time operation, and...
3
by: subramanian100in | last post by:
Consider vector<stringv; If we call, v.erase(v.end()) this invokes undefined behaviour. But, if we call
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.