Search code examples
c++multimap

How to avoid duplicate pairs / find a pair in multimap?


I have some (working) code that uses a multimap<string,string>. I'd like to change it to disallow duplicate values on the same key (obviously different values on the same key are fine, otherwise I wouldn't use a multimap).

Surprisingly the type doesn't seem to have a built-in way to avoid duplicates nor to find a key-value pair (only to find a key). But I figure someone on SO must have a ready-made workaround. Anyone?


Solution

  • Here's what I came up with:

    template<class K, class V>
    typename multimap<K, V>::const_iterator find_pair(const multimap<K, V>& map, const pair<K, V>& pair)
    {
        typedef multimap<K, V>::const_iterator it;
        std::pair<it,it> range = map.equal_range(pair.first);
        for (it p = range.first; p != range.second; ++p)
            if (p->second == pair.second)
                return p;
        return map.end();
    }
    template<class K, class V>
    bool insert_if_not_present(multimap<K, V>& map, const pair<K, V>& pair)
    {
        if (find_pair(map, pair) == map.end()) {
            map.insert(pair);
            return true;
        }
        return false;
    }
    

    (This is not efficient when there are a large numbers of values attached to a single key, but in my case there are very few values on each key.)