Python 的 setdefault 的 C++(STL 映射)等效方法

C++ (STL map) equivalent method to Python's setdefault

很可能这个问题已经被问过了。找不到。

每次我定义一个std::map并想给它插入一些值,我使用这段代码:

using IntVector = vector < int > ;
map<int, IntVector> mapTmp;

int iKey = 7;
int iVal = 9;
if (mapTmp.find(iKey) == mapTmp.end())
    mapTmp.insert(pair<int, IntVector>(iKey, IntVector()));
mapTmp[iKey].push_back(iKey);

让我烦恼的是 3 行:

if (mapTmp.find(iKey) == mapTmp.end())
    mapTmp.insert(pair<int, IntVector>(iKey, IntVector()));
mapTmp[iKey].push_back(iVal);

Python 提供了一个非常有用的 dict 函数,称为:setdefault,它基本上将这 3 行组合成一个漂亮的行。假设我想用 C++ 编写它,它将是:

mapTmp.setdefault(iKey, IntVector()).push_back(iVal);

问题

  1. C++是否提供这样的功能?
  2. 如果不是,大家是不是一直写这3行?

C++ 标准库定义的映射有一些违反直觉的行为,即仅调用 operator[] 就可以 改变 数组。换句话说,你的 "if not in map then insert a default" 逻辑完全是多余的——下面两段是等价的:

if (mapTmp.find(iKey) == mapTmp.end())
    mapTmp.insert(pair<int, IntVector>(iKey, IntVector()));
mapTmp[iKey].push_back(iVal);

和:

mapTmp[iKey].push_back(iVal);

第二种情况,如果iKey在map中不存在,则先默认初始化。对于向量,这与插入空向量相同。

对于Python的setdefault涵盖的一般情况,我一无所知。您可以通过为地图提供自定义分配器来获得效果,但我不推荐这样做。