0

I have a std::map<int64_t, int64_t> foo;.. it is fed daily with XX amount of pairs (not defined, they may be 1 or 1000).
To reduce memory usage, i want to delete no more useful elements of my map. i did this:

    map<int64_t, int64_t> tmpMap;
    // Copy into a new temporary map only elements to keep
    for (map<int64_t, int64_t>::iterator it = foo.begin(); it != foo.end(); ++it)
    {
        // the condition decides whether a pair is still useful or not
        if ([...]) 
        {
            pair<int64_t, int64_t>  tmpPair(it->first, it->second);
            tmpMap.insert(tmpPair);
        }
    }
    // Clear the main map
    foo.clear();
    // Copy tmpMap (which contains only useful elements) into the main map
    foo.insert(tmpMap.begin(), tmpMap.end());
    tmpMap.clear();

Any suggestion on how to reach my goal in a better way in terms of resource usage, considering that foo may have 500/600 pairs of int64_t and these line are called each time foo is fed?

Thanks (and sorry for my english)

braX
  • 11,506
  • 5
  • 20
  • 33
sciakysystem
  • 97
  • 1
  • 2
  • 10
  • 3
    Is there a reason you're not just using the [`erase`](http://en.cppreference.com/w/cpp/container/map/erase) method ? – Sander De Dycker Feb 20 '15 at 10:24
  • You can use erase, but you must be careful, since erasing an iterator invalidates it. Also, do you have to worry about concurrency? In addition, unless you are running your code on an embedded device, 600 pairs is nothing. Obviously, this solution is not efficient if the data size is considerably larger. – Andre Feb 20 '15 at 10:30
  • Im not so familiar with std::map and i found this way easier. In particular, im not sure of what happen with the map's keys once you erase the first XXX elements.So I thought this way gives me a "clearer" map. But im here for suggestions :) @Andre iterators invalidation is exactly the reason why i used a tmpMap. Since, as told above, im not so familiar with maps, deal with iterators invalidation is something not so known by my brain. – sciakysystem Feb 20 '15 at 10:33
  • [this](http://stackoverflow.com/questions/800955/remove-if-equivalent-for-stdmap) question might be helpful. – Daniel Feb 20 '15 at 10:34

1 Answers1

3

There is no need to create a temporary; just iterate over the std::map and conditionally call std::map::erase. Here is an example:

std::map<int,int> my_map {{1, 2}, {2, 3}, {3, 4}};
std::cout << my_map.size() << std::endl; // 3
auto begin = std::begin(my_map);
while (begin != std::end(my_map)) {
    if (begin->first == 2) {
        begin = my_map.erase(begin); // C++11
    } else {
        ++begin;
    }
}
std::cout << my_map.size() << std::endl; // 2
Daniel
  • 8,179
  • 6
  • 31
  • 56