将一对插入地图并增加计数?

问题描述 投票:2回答:1

我正在使用的代码库使用map::operator[]来插入和递增该条目中的项目数量(这对我来说是一个知识差距)。这是一个例子:

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

我想要做的是将ID添加到插入内容,同时保留上面语法中的增量行为。

我的新地图看起来像这样:

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

我很难看到如何使用我的新地图获得相同的功能。这基本上是我的目标(显然是错误的,因为“++”不能以这种方式使用):

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

我错过了更好的方法吗?

c++ dictionary std-pair
1个回答
2
投票

您可以通过使用insert方法及其返回的it / bool对来执行此操作,从而提供单个查找(按名称),在初始查找时设置employee id,然后分别递增计数器。

像这样的东西:

auto pr = namesMapWithID.insert(std::make_pair(firstName,
    std::make_pair(employeeID, size_t())));
++pr.first->second.second;
© www.soinside.com 2019 - 2024. All rights reserved.