Re: Erase in a map
- From: Ulrich Eckhardt <eckhardt@xxxxxxxxxxxxxx>
- Date: Tue, 20 Mar 2007 12:56:50 +0100
Charles Zhang wrote:
I want to erase items in a map based on some criteria. However, as soon
as the erase is called, iterator become invalid. I would like someone
to tell me the better way to do it.
Here is the source code I am using, and it is crashing.
for ( pos = connectionMap.begin(); pos != connectionMap.end(); ++pos){
ConnectionInfo* conn = pos->second;
if ( current - conn->lastRequestTime > 60 * timeOut ) {
connectionMap.erase(pos);
}
}
To overcome the problem, I start the loop from the beginning after a
item is removed. But this is too slow.
The typically used solution is this:
while(it!=end)
if(predicate(*it))
container.erase(it++);
else
++it;
Note the use of postfix and prefix increment.
Uli
.
- References:
- Erase in a map
- From: Charles Zhang
- Erase in a map
- Prev by Date: Re: Erase in a map
- Next by Date: memory usage problem
- Previous by thread: Re: Erase in a map
- Next by thread: local type in template - C2918
- Index(es):
Relevant Pages
|
Loading