NeatoBandito
NeatoBandito

Reputation: 110

Insert a pair into a map and increase the count?

The codebase I'm working in uses the map::operator[] to insert and increment the count of items in that entry by one (this is a knowledge gap for me). Here's an example:

map<string, size_t> namesMap;
namesMap[firstName]++;

What I want to do is tack on an ID to the insert while retaining the increment behavior in the syntax above.

My new map would look like this:

map<string, pair<int, size_t>> namesMapWithID;

I'm struggling to see how to get the equivalent functionality with my new map. This is basically my goal (obviously wrong since "++" cannot be used this way):

namesMapWithID.insert(firstName, make_pair(employeeID, ++));

Is there a better approach that I'm missing?

Upvotes: 2

Views: 97

Answers (1)

WhozCraig
WhozCraig

Reputation: 66254

You can do this via using the insert method along with the it/bool pair it returns, thereby delivering a single lookup (by name), setting the employee id if on the initial lookup, and then incrementing the counter respectively.

Something like this:

auto pr = namesMapWithID.insert(std::make_pair(firstName,
    std::make_pair(employeeID, size_t())));
++pr.first->second.second;

Upvotes: 2

Related Questions