如何遍历多映射并打印按键分组的值
How to iterate through a multimap and print values grouped by key?
我有std::multimap<string, MyObject*> dataMap;
,其中键是MyObject.name
,所有MyObjects都存储在std::vector<MyObject>
中。
在填充映射后,我需要打印按相同键分组的dataMap
的内容,其中我首先需要在dataMap.count(MyObject.name)
的帮助下的相同键的数量,然后需要使用该键的所有值。
我想使用两个for loops
,其中第一个循环遍历"密钥组名称"并计算属于该组的所有密钥,另一个for loop
遍历某个组中的所有密钥并打印MyObject.information
for(//iterate through group key names){
//print number of key occurences
for(//iterate through a certain group{
//print MyObject.information for all the keys in a group
}
}
问题是,我真的不知道该如何实现,或者更确切地说,我该如何根据自己的意愿使用迭代器。有什么想法吗?
编辑:从提供的链接我创建了这个
for(std::multimap<string, MyObject*>::const_iterator itUnq = dataMap.cbegin();
itUnq != dataMap.cend(); itUnq = dataMap.upper_bound(itUnq->first)){
std::cout << dataMap.count(itUnq->second->name)
<< std::endl;
std::pair <std::multimap<string, MyObject*>::const_iterator,
std::multimap<string, MyObject*>::const_iterator> groupRange;
groupRange = dataMap.equal_range(itUnq->second->code);
//iterate through keys inside the group
for(std::multimap<string, MyObject*>::const_iterator itGroup = groupRange.first;
itGroup != groupRange.second; ++itGroup){
std::cout << itGroup->second->information
}
评论?
根据我对您的问题的了解,您可以使用std::multimap::equal_range来实现它。
有点像这样:
#include <map>
#include <ctime>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
struct MyObject
{
std::string name;
int information;
MyObject(const std::string& name, int information)
: name(name), information(information) {}
};
int main()
{
std::srand(std::time(0));
std::vector<MyObject> dataVec;
std::multimap<std::string, MyObject*> dataMap;
// Give each object a random letter
// between A-J as a name and some data
for(auto i = 0; i < 10; ++i)
dataVec.emplace_back(std::string(1, 'A' + std::rand() % 10), i);
// Fill dataMap from dataVec
for(auto&& data: dataVec)
dataMap.emplace(data.name, &data);
// Select the correct type for calling the equal_range function
decltype(dataMap.equal_range("")) range;
// iterate through multimap's elements (by key)
for(auto i = dataMap.begin(); i != dataMap.end(); i = range.second)
{
// Get the range of the current key
range = dataMap.equal_range(i->first);
// Now print out that whole range
for(auto d = range.first; d != range.second; ++d)
std::cout << d->first << ": " << d->second->information << 'n';
}
}
在此处运行
如果这不是你想要的,也许它仍然会给你解决具体问题的想法。
相关文章:
- 打印无序映射的第二个元素,即集合
- 打印对象的映射,其中另一个对象作为键
- 类中的 C++ 全局映射,不要打印 map 元素
- 在多重映射中打印一次重复值
- 如何打印包含整数和整数集的std::映射
- 打印出映射键值,其中键是结构变量 c++
- Ostream打印内存映射,然后倾倒核心
- 打印包含多映射的deque
- 将元素插入具有设定值的映射并打印该集
- 打印字符串向量的映射
- 打印多映射<字符串,矢量<string>>?
- 如何仅 n 次打印出多映射中的元素
- 在 C 语言中打印映射/过滤器/减少函数时出现问题
- 我可以用cout而不是迭代器循环打印STL映射吗?
- 使用 std::transform 打印映射<字符串、矢量<字符串*时出错> >
- 在c++中按降序打印映射值
- 如何遍历多映射并打印按键分组的值
- 将STL映射打印为表格
- 如何在多映射中按排序顺序打印键的值
- 打印包含映射的结构