具有单个键的多个值的 STL 集合

STL collection with multiple values for a single key

来自 sql 我有一个输出:

标识值
第123话
124 xxx
124 年
125 xxx

我在 C++ 代码中处理此输出,我想在其中使用 123、125 id(唯一)和 124,它们分别具有多个值。

基本上,我想分别存储唯一和多值 ID,然后再分别检索它们。

我可以使用任何 stl 容器。

假设 container1 存储唯一值

第123话
125 xxx

容器 2

124 xxx
124 年

在 map 中,我可以有唯一的键值对:(123->xxx)(125->xxx)124->xxx,yyy 分别吗?

有人可以帮助我创建更好的设计吗?

最简单的方法是 std::map<int, std::vector<std::string> >(将 std::string 替换为您的类型),如下所示:

#include <iostream>
#include <string>
#include <map>
#include <vector>

int main()
{
  std::map< int, std::vector< std::string > > map; // could use std::unordered_map as well for O(1) lookup if order of keys doesn't matter
  map[123].push_back("AAA");
  map[124].push_back("BBB");
  map[124].push_back("CCC");
  map[125].push_back("DDD");
  for(auto itr = map.begin(); itr!=map.end(); itr++) {
      std::cout<<itr->first<<":";
      for(auto vitr = itr->second.begin(); vitr != itr->second.end(); vitr++){
          std::cout<<*vitr<<",";
      }
      std::cout<<std::endl;
  }
}

输出:

123:AAA,
124:BBB,CCC,
125:DDD,

从您的描述来看,有点不清楚是否可以将每个键(无论有多少条目)视为值列表。但如果是这样,这是最直接的方法。

已经有对这种容器的标准支持。

std::multisetstd::multimap 就是您要找的。

http://en.cppreference.com/w/cpp/container/multiset http://en.cppreference.com/w/cpp/container/multimap