首页 > 解决方案 > 我可以将一个值放入存储在 C++ 中的映射中的向量中吗?

问题描述

我想知道是否可以将一个值放入存储在地图中的向量中。

目前我这样做......

std::map<std::string, std::vector<std::string>> my_collection;
my_collection["Key"].push_back("MyValue");

我在想我可以执行以下操作,并且 C++ 会足够聪明地意识到它应该将它添加到向量中......但是我得到了一个内存编译错误。

my_collection.emplace("Key", "MyValue");

标签: c++emplace

解决方案


您可以创建一个向量,将其置入其中,然后移动该向量。这样您的对象就不会被复制或移动:

std::map<std::string, std::vector<std::string>> my_collection;
std::vector<std::string> temp;
temp.emplace_back("MyValue");
my_collection["Key"] = std::move(temp);

或者,您在地图中创建矢量并处理参考:

std::map<std::string, std::vector<std::string>> my_collection;
auto &keyVec = my_collection["Key"];
keyVec.emplace_back("MyValue");

方便地,这归结为:

std::map<std::string, std::vector<std::string>> my_collection;
my_collection["Key"].emplace_back("MyValue");

推荐阅读