首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在multimap中用同一行打印相同键的值,在下一行打印不同键的值

在multimap中用同一行打印相同键的值,在下一行打印不同键的值
EN

Stack Overflow用户
提问于 2020-03-27 13:11:37
回答 1查看 700关注 0票数 0

我有一个具有键值对的multimap,如下所示:

multiMap-3 = {'h'}

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

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

我希望打印输出,以便第一行具有键'-3‘的所有值,第二行有键'-2’的所有值,最后一行具有与键'-1‘对应的所有值。

我使用以下代码,但它会打印新行中的每个元素

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-27 13:11:37

为了在一行中打印特定键的所有值,我们使用multimap::lower_bound()和multimap::upper_bound()函数。

代码语言:javascript
复制
#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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60886719

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档