繁体   English   中英

矢量作为哈希地图中的键值对

[英]Vector as key value pair in Hash map

我正在尝试使用std :: vector类型的键值对之一在C ++中创建一个hash_map。 我没有得到的是如何在哈希表的向量部分插入多个值?

hash_map<string, int> hm;
hm.insert(make_pair("one", 1));
hm.insert(make_pair("three", 2));

上面的示例是使用没有矢量的哈希映射作为密钥对值的简单方法。

以下示例使用Vector。 我试图为每个对应的字符串值添加多个int值,例如=>“one”&(1,2,3)而不是“one”&(1)。

hash_map<string, std::vector<int>> hm;
hm.insert(make_pair("one", ?)); // How do I insert values in both the vector as well as hash_map
hm.insert(make_pair("three", ?)); // How do I insert values in both the vector as well as hash_map

如果你想知道为什么在这里使用向量,基本上我正在尝试添加多个值而不是单个int值foreach相应的字符串值。

hash_map<string, std::vector<int>> hm;
hm.insert(make_pair("one", vector<int>{1,2,3})); // How do I insert values in both the vector as well as hash_map
hm.insert(make_pair("three", vector<int>{4,5,6}));

您可以执行以下操作:

std::unordered_map<std::string, std::vector<int>> hm;
hm.emplace("one", std::vector<int>{ 1, 2, 3 });

如果您想稍后添加它,您可以执行:

hm["one"].push_back(4);

在这里编译

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

int main()
{
  std::unordered_map<std::string, std::vector<int> > hm;
  hm["one"]={1,2,3};
  hm["two"]={5,6,7};
  for (const auto&p : hm)
  {
     std::cout<< p.first << ": ";
     for (const auto &i : p.second)
        std::cout<< i << ", ";
     std::cout<<  std::endl;
  }
}

这个输出:

二:5,6,7,

一:1,2,3,

以前的答案基本上是对的(我刚刚没有测试过)。 在核心中,它们使用vector构造函数,该构造函数采用初始化列表,这是直接创建枚举值的向量的唯一方法。 不过,我想展示我认为更好的方法来做你真正想要的 - 为给定的字符串键设置一个新值。

此容器的operator[string]返回相应值的引用,此处为vector<int> 如果密钥是新的,它首先创建一个新值(向量),然后插入该对。 然后, vector<int>operator=将从初始化列表中分配。 我会说你应该使用这个直接变体的其他变体,只有当你找到一个不使用它的严重理由时,因为这更加惯用且更直接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM