I have a data structure represented by a vector of maps, all of which have the same template type. Inserting and reading works fine - however, for some reason, updates do nothing. I tried the methods described here, and they work fine - if I just use the map itself. However, when the map is in the vector, the element is found but not updated. Below, I have provided a minimal example.
#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;
}
So my questions are:
- Why does this fail? I'm sure it's some kind of pointer logic I don't understand.
- What do I have to change to make it work?