-1

I'm trying to remove elements that have the same key and value in a multimap. This is my code for now. After deleting the element, I get exception.

multimap<string, CStudent> m_StudentMap;
void removeDuplicates() {
    for (auto it1 = m_StudentMap.begin(); it1 != --m_StudentMap.end(); it1++) {
        for (auto it2 = next(it1, 1); it2 != m_StudentMap.end(); it2++) {
            if (it1->first == it2->first) {
                if (it1->second == it2->second) {
                    m_StudentMap.erase(it2);
                }
            }
        }
    }
}

1 Answers1

0

You were nearly right, but the trick with erasing elements in maps while iterating is to capture the new iterator returned by erase. I've also generalised the function so it can be used on an argument rather than being limited to m_StudentMap, and stopped the inner loop as soon as the keys diverge.

template <typename K, typename V>
void removeDuplicates(std::multimap<K, V>& mmap)
{
    if (mmap.size() < 2) return;
    for (auto it = mmap.begin(); it != prev(mmap.end()); ++it)
        for (auto it2 = next(it); it2 != mmap.end() && it2->first == it->first; )
            if (it->second == it2->second)
                it2 = mmap.erase(it2);
            else
                ++it2;
}

You can see it run / fork it etc. here.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252