为什么将此对向量< map< int,int>>中的地图进行更新.失败
Why does this update to a map in a vector<map<int, int>> fail?
i具有由地图向量表示的数据结构,所有这些都具有相同的模板类型。插入和阅读效果很好 - 但是,由于某些原因,更新无能为力。我尝试了此处描述的方法,它们工作正常 - 如果我只使用地图本身。但是,当地图在向量中时,找到元素但未更新。下面,我提供了一个最小的例子。
#include <iostream>
#include <map>
#include <vector>
#include <optional>
std::vector<std::map<int, int>> vec = std::vector<std::map<int, int>>();
void insert_or_update( int key, int value ) {
for ( std::map<int, int> map: vec ) {
auto location = map.find( key );
if ( location != map.end()) {
location->second = value;
std::cout << "This should update the value, but doesn't" << std::endl;
return;
}
}
// Insert, if no map currently contains the key
std::cout << "This value is new" << std::endl;
vec.back().insert( {key, value} );
}
int get_key( int key ) {
for ( std::map<int, int> map: vec ) {
auto location = map.find( key );
if ( location != map.end()) {
return location->second;
}
}
std::cout << "This value doesn't exist yet" << std::endl;
return 0;
}
int main()
{
std::map<int, int> map = std::map<int, int>();
vec.push_back( map );
std::cout << get_key(3) << std::endl;
insert_or_update(3, 3);
std::cout << get_key(3) << std::endl;
insert_or_update(3, 5);
std::cout << get_key(3) << std::endl;
std::cout << "Update in list failed, do it manually..." << std::endl;
auto location = map.find( 3 );
location->second = 5;
std::cout << location->second << std::endl;
return 0;
}
所以我的问题是:
- 为什么失败?我确定这是我不理解的某种指针逻辑。
- 我必须更改它才能使它起作用?
因为这一行:
for ( std::map<int, int> map: vec ) {
通过Value 中的vec
中的每个元素进行枚举。它正在制作for循环的每次迭代中的地图的复制。因此,您将新值插入副本,而不是实际上是在矢量中的项目中。这可能是您想要的 - 通过参考列举项目:
for ( std::map<int, int>& map: vec ) {
或简单:
for ( auto& map: vec ) {
在get_key
您的功能insert_or_update
在for
循环中制作vec
的副本:
for ( std::map<int, int> map: vec ) {
auto location = map.find( key );
if ( location != map.end()) {
location->second = value;
std::cout << "This should update the value, but doesn't" << std::endl;
return;
}
}
如果要更改vec
,则需要参考而不是副本:
for ( std::map<int, int> & map: vec ) {
//...
}
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中