The*_*red 8 c++ key count multimap
我有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
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,我真的不知道如何实现这个,或者我将如何使用迭代器来实现我的意愿.有任何想法吗?
编辑:从提供的链接我创建了这个
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
}
Run Code Online (Sandbox Code Playgroud)
评论?
根据我对你的问题的理解,你可以使用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';
}
}
Run Code Online (Sandbox Code Playgroud)
如果这不是你想要的,也许它仍会给你如何解决你的具体问题的想法.
| 归档时间: |
|
| 查看次数: |
13254 次 |
| 最近记录: |