c++ - 我可以将一个值放入存储在 C++ 中的映射中的向量中吗?
问题描述
我想知道是否可以将一个值放入存储在地图中的向量中。
目前我这样做......
std::map<std::string, std::vector<std::string>> my_collection;
my_collection["Key"].push_back("MyValue");
我在想我可以执行以下操作,并且 C++ 会足够聪明地意识到它应该将它添加到向量中......但是我得到了一个内存编译错误。
my_collection.emplace("Key", "MyValue");
解决方案
您可以创建一个向量,将其置入其中,然后移动该向量。这样您的对象就不会被复制或移动:
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");
推荐阅读
- go - Go 中的转义反引号(exec.Command 中使用的字符串)
- makefile - 你能优先考虑makefile目标吗?
- excel - 拔下显示器后 ActiveCell.Top 的 VBA 值错误
- python - 协方差矩阵的主轴与其角度不对齐
- vb.net - 我无法使用 KeyEventArgs 做我想做的事情
- python - django has_perm 总是假的
- django - Django 拒绝没有 nginx/apache 的大请求
- windows - Windows 上的 Apache Flink
- php - 致命错误:赋值只能发生在 C:\xampp\htdocs\dogs\application\controllers 中的可写值上
- php - laravel黄昏宏抛出的BadMethodCallException