Search code examples
c++c++17multimap

Print the values of the same key in same line in multimap and of different keys in next line


I have a multimap which have key-value pairs as following:

multiMap[-3] = {'h'}

multiMap[-2] = {'d','j','m'}

multiMap[-1] = {'b','f','i','p'}

I wish to print the output such that the first line has all the values for the key '-3', the second line has all the values for the key '-2' and the last line has all the values corresponding to the key '-1'.

I use the following code, but it prints each element in a new line

int main()
{
    multimap<int,char> multiMap;
    multimap.insert({-3,'h'});
    //And so on for all the key-value pairs

    //To print the multimap:
    for(auto i = multiMap.begin(); i != multiMap.end(); i++)
        cout << i->second << "\n";
    return 0;
}

Solution

  • For printing all the values of a particular key in one line, we use multimap::lower_bound() and multimap::upper_bound() functions.

    #include <iostream>
    #include <map>
    using namespace std;
    
    int main()
    {
        multimap<int,char> myMap;
    
        myMap.insert({-1,'b'});
        myMap.insert({-1,'f'});
        myMap.insert({-1,'i'});
        myMap.insert({-1,'p'});
    
        myMap.insert({-2,'d'});
        myMap.insert({-2,'j'});
        myMap.insert({-2,'m'});
    
        myMap.insert({-3,'h'});
    
        auto i = myMap.begin();
    
        for(; i != myMap.end();)
        {
            auto itr = myMap.lower_bound(i->first);
            for(; itr != myMap.upper_bound(i->first); itr++)
                cout << itr->second << " ";
            i = itr;    //This skips i through all the values for the key: "i->first" and so it won't print the above loop multiple times (equal to the number of values for the corresponding key).
            cout << "\n";
        }
        return 0;
    }