为什么将此对向量< map< int,int>>中的地图进行更新.失败

Why does this update to a map in a vector<map<int, int>> fail?

本文关键字:lt gt int 地图 失败 更新 map 为什么 向量      更新时间:2023-10-16

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;
}

所以我的问题是:

  1. 为什么失败?我确定这是我不理解的某种指针逻辑。
  2. 我必须更改它才能使它起作用?

因为这一行:

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_updatefor循环中制作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 ) {
    //...
}