如何遍历多映射并打印按键分组的值

How to iterate through a multimap and print values grouped by key?

本文关键字:打印 映射 何遍历 遍历      更新时间:2023-10-16

我有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';
    }
}

在此处运行

如果这不是你想要的,也许它仍然会给你解决具体问题的想法。