Re: Erase in a map



On Mar 16, 9:35 pm, Charles Zhang <CharlesZh...@xxxxxxxxxxxxxxxxx>
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.

Thanks

Charles Zhang

use standard library:
#include <algorithm>

/*assuming that TConnectionMap implements std::map<long,ConnectionInfo
*> */

typedef std::map<long,ConnectionInfo *> TConnectionMap;

struct ConnExpired{//define a predicate class;

ConnExpired(const long cur): current(cur) {};

bool operator () (const TConnectionMap::value_type& conn)
const
{
return current - conn.second->lastRequestTime > 60 *
timeOut ;
};

private:
const long current;
};

{//somewhere in the code:
TConnectionMap connectionMap;
long current;
std::remove_if
(connectionMap.begin(),connectionMap.end(),ConnExpired(current));
};

and do not worry about the validity of the iterators because the
STL(standard template library) is responsible for it.

.



Relevant Pages

  • Re: const question
    ... >> I'd advice against that. ... My const function is to ... There the const iterator ... it seems to me that if a member function is returning a non-const ...
    (alt.comp.lang.learn.c-cpp)
  • Re: const question
    ... > I'd advice against that. ... > than simply removing 'const' everywhere. ... There the const iterator becomes problematic. ... The problem as I understand it is that a const function won't let me ...
    (alt.comp.lang.learn.c-cpp)
  • Re: const question [C++]
    ... Mark P wrote in message ... ... >> than simply removing 'const' everywhere. ... There the const iterator becomes problematic. ... >The problem as I understand it is that a const function won't let me ...
    (alt.comp.lang.learn.c-cpp)
  • Re: const question
    ... > 'const' everywhere. ... 'const' member functions to mutate *it*. ... [of an iterator which I don't think can be done]. ... > any description of that no advice can be given. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Collections and Decorators
    ... take care of everything? ... iterator is one example. ... the source code but before I did that I wanted to ask this so as to ... static class SynchronizedCollection ...
    (comp.lang.java.programmer)

Loading