So most likely this question had been asked already. Couldn't find it.
Every time I define a std::map and want to insert some value to it, I use this piece of code:
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);
What annoys me is the 3 lines:
if (mapTmp.find(iKey) == mapTmp.end())
mapTmp.insert(pair<int, IntVector>(iKey, IntVector()));
mapTmp[iKey].push_back(iVal);
Python offer a very useful dict function called: setdefault, that essentially combine those 3 lines into one beautiful line. Say I want to write it in C++, it would be:
mapTmp.setdefault(iKey, IntVector()).push_back(iVal);
Questions
- Does
C++
offer such functionality? - If not, does everyone write those 3 lines all the time?