Reputation: 1678
I have a boost::unordered_map which I want to modify the value of a particular key. I have seen the question here.
what makes my question different is that in my map key is a simple int and my value is std::vector. I want to update this value by inserting a new PoitCoord at the second position of the vector.
One solution is like that:
auto it = map.find(key);
if(it != map.end())
{
std::vector<PointCoord> pntcrds = it->second;
pntcrds.insert((pntcrds.begin()+1), new_value);
it->second = pntcrds;
}
I am wondering if there is less verbose solution.
Upvotes: 1
Views: 767
Reputation: 20056
There is indeed a very simple solution, that covers all the scenarios you might think about. And it is
myMap[key].insert(pntcrds.begin()+1);
If the key does not exist, it will be inserted. otherwise, the value will be updated to the new one;
But you must make sure you have at least one element in your vector. Otherwise, it will crash.
A similar trick would be
myMap[key].push_back(new_value); // appends to the end of the vector
Upvotes: 1
Reputation: 4626
The map does not have anything to do with your insertion, if I understand your question correctly. You are only modifying a vector which happens to be stored in a map. You are not modifying the key of a map, but one of it's values.
So the short solution would be:
auto it = map.find(key);
if(it != map.end() && !it->second.empty() )
{
it->second.insert( (pntcrds.begin()+1), new_value);
}
If you know that the key exists in your map, you can shorten this to:
std::vector<PointCords> & pntCords = map[key];
if( ! pntCords.empty() )
pntCords.insert( pntCords.begin()+1, new_value );
NB: If you use the second method and the key does not yet exist, a default constructed (=empty) std::vector<PointCords>
will be inserted into the map.
Upvotes: 2
Reputation: 600
You have to find the key iteration position then update directly the found key by
it->second.insert( (pntcrds.begin()+1), new_value);
but you have to be sure that you've found the iteration and as @Johannes said your vector is not empty.
Upvotes: 1