Выведите значения одного и того же ключа в одной строке в мультикарте и разных ключей в следующей строке - PullRequest
0 голосов
/ 27 марта 2020

У меня есть мультикарта с парами ключ-значение:

multiMap [-3] = {'h'}

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

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

I wi sh для печати вывод такой, что в первой строке есть все значения для ключа '-3', во второй строке есть все значения для ключа '-2', а в последней строке есть все значения, соответствующие ключу '-1'.

Я использую следующий код, но он печатает каждый элемент в новой строке

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;
}

1 Ответ

1 голос
/ 27 марта 2020

Для печати всех значений определенного ключа в одной строке мы используем функции multimap :: lower_bound () и multimap :: upper_bound ().

#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;
}
...