-1

I've read a lot and couldn't find any answer to this issue. I have a multimap, which contains pairs of <Class object, enum class> and using std::multimap.equal_range() I'm getting the range of all of the duplicate keys in it. The next step is that I want to erase all but one of those duplicates. My following code erases all of them, leaving no pairs with the given key. Is there anyway that I can simply erase all but one of them?

void removeDuplicates( const string& strToRemove ) {
        CFile obj (strToRemove, 0);       
            pair <multimap<CFile,Filetype>::iterator, multimap<CFile,Filetype>::iterator> ret;
            ret = m_DirectoryMap.equal_range(obj);
            for (multimap<CFile,Filetype>::iterator it=ret.first; it!=ret.second; ++it) {
                it = m_DirectoryMap.erase(it);

            }
}

Like I mentioned, with the following code if I have 3 pairs which have the same keys, they're all getting removed. I want to remove n-1 duplicates, not n.

meitriksx
  • 3
  • 2
  • `multimap::iterator it=ret.first+1` ? – Simon Kraemer Mar 02 '16 at 11:45
  • I doubt a "CFile" is a proper key! –  Mar 02 '16 at 11:46
  • `auto it = ret.first+1` doesn't work, already tried that and it gives an error. @DieterLücking, what do you mean by that? CFile is class with member variables string and int. I am instantiating an object of that class with the string that I'm passing as argument in the function and then getting the equal_range of those objects... – meitriksx Mar 02 '16 at 11:52

1 Answers1

0

Incrementing it after it=mymap.erase(it) doesn't look right to me.

You should do this

auto it=ret.first;
if (it!=ret.second)
{
    ++it;
    while (it!=ret.second)
        it=mymap.erase(it);
}
anukul
  • 1,922
  • 1
  • 19
  • 37
  • `error: no match for 'operator+' in 'ret.std::pair >, std::_Rb_tree_iterator > >::first + 1'|` – meitriksx Mar 02 '16 at 11:54
  • 2
    It doesn't work with the `(it < ret.second)` condition. An error `no match for operator<` seems to happen. However, when I change it to `(it != ret.second)` it seems to work just fine. Thank you for your help. – meitriksx Mar 02 '16 at 11:58
  • Take care of the condition when `ret.first==ret.second` is true. – anukul Mar 02 '16 at 12:02