Search code examples
c++containersmultimap

How can i erase duplicated elements from a multimap<int, std::pair<int, bool>>?


I have a multimap with duplicates. When I finished the collection of the elements i would like to erase the dups.

Here is the container:

std::multimap<int, std::pair<int, bool>> container;

This following code is inside an iteration.(it is a simpler version of the original)

container.emplace(LeafId, std::make_pair(NodeId, isElectronic));

Is it good solution?

std::pair<int, std::pair<int, bool>> lastValue {-1 , {-1, -1}}; 
    for (auto it = container.cbegin(); it != container.cend();)
    {
        if (it->first == lastValue.first && it->second == lastValue.second)
        {
            it = container.erase(it);
        } else
        {
            lastValue = *it;
            ++it;
        }
    }

Solution

  • Is it good solution?

    Unless you keep internal pair sorted inside multimap, no it is not a good solution as it would miss duplicates. If you can change data type then you can use:

    std::map<int, std::vector<std::pair<int, bool>>>
    

    instead of std::multimap and then for each element sort vector and remove duplicates using standard algorithms as described here Removing duplicates in a vector of strings

    if you cannot I suggest to use additional std::set or std::unordered_set:

    std::set<std::pair<int, bool>> tset;
    int lastValue = 0;
    for (auto it = container.cbegin(); it != container.cend();)
    {
        if( it->first != lastValue ) {
            tset.clear();
            lastValue = it->first;
        }
    
        if( !tset.insert( it->second ).second )
            it = container.erase( it );
        else
            ++it;
    }