Search code examples
c++dictionaryiteratormultimap

Is there a .at() equivalent for a multimap?


Is there any way to get an iterator to a multimap, for specific keys? For example:

multimap<string,int> tmp;
tmp.insert(pair<string,int>("Yes", 1));
tmp.insert(pair<string,int>("Yes", 3));
tmp.insert(pair<string,int>("No", 5));
tmp.insert(pair<string,int>("Maybe", 1));
tmp.insert(pair<string,int>("Yes", 2));

multimap<string,int>::iterator it = tmp.at("Yes);

Then I could use it for the work I want to do. Is this possible in C++? Or do we have to just cycle through the multimap, element by element, and check for the key before doing the work?


Solution

  • multimap<Key, T> only sort elements by its Key, so we can only find all the elements whose key value equals "Yes", then check each element one by one.

    typedef multimap<string,int>::iterator Iterator;
    pair<Iterator, Iterator> iter_range = tmp.equal_range("Yes");
    Iterator it;
    for (it = iter_range.first; it != iter_range.second; ++it) {
        if (it->second == 3) {
            break;
        }
    }
    if (it != tmp.end()) {
        tmp.erase(it);
    }
    

    In fact it's better to use multiset<T> in this case:

    multiset< pair<string, int> > temp;
    temp.insert(make_pair("Yes", 1));
    temp.insert(make_pair("Yes", 3));
    multiset< pair<string, int> >::iterator iter = temp.find(make_pair("Yes", 1));
    if (iter != temp.end()) {
        temp.erase(iter); // it erase at most one element
    }
    temp.erase(make_pair("Yes", 3)); // it deletes all the elements that equal to make_pair("Yes", 3)