简体   繁体   中英

Short function to insert into a std::map<int, std::vector<int>>

I find myself often in the situation where I write the following code:

std::map<int, std::vector<int>> dict;

void insert(int key, int val) {
  if (dict.find(key) == dict.end()) {
    dict[key] = std::vector<int>();
  }
  dict[key].push_back(val)
}

Is there a less wordy way (in C++11) of writing this insert function?

I don't think your function is particularly wordy, but in this scenario it could simply be replaced by dict[key].push_back(val) because operator[] on a map default constructs the value if it doesn't exist. You don't need the if block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM