Reputation: 816
I have a map, which I want to fulfill by max values.
What I want:
1. if key
doesn't exist or value > mymap[key]
then mymap[key] = value
2. otherwise, I don't want to rewrite mymap[key]
value
I have strong impression that everything written below could be done in one line with the help of triplet operator
if (mymap.find(key) != mymap.end())
{
mymap[key] = value;
}
else
{
if (value > mymap[key]) mymap[key] = value;
}
I'd do smth like
mymap[key] = value > mymap[key] ? value : mymap[key];
but if key
doesn't exists this would create mymap[key] = 0
, and the problem is that value
could be negative.
Any ideas? Thanks a lot for your help in advance!
Upvotes: 0
Views: 48
Reputation: 1918
As mentioned in the comments, you search the map for a key several times. Generally it is best to save the result of find in order to use it for manipulations later so you aren't researching the map for the key each time.
How about this?
const auto it = mymap.find(key);
if (it != mymap.end())
{
it->second = std::max(value, it->second);
}
else
{
mymap.emplace(key, value);
}
Upvotes: 1