我有一个具有键值对的multimap,如下所示:
multiMap-3 = {'h'}
multiMap-2 = {'d','j','m'}
multiMap-1 = {'b','f','i','p'}
我希望打印输出,以便第一行具有键'-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;
}发布于 2020-03-27 13:11:37
为了在一行中打印特定键的所有值,我们使用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;
}https://stackoverflow.com/questions/60886719
复制相似问题