user695652
user695652

Reputation: 4275

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?

Upvotes: 2

Views: 506

Answers (1)

kmdreko
kmdreko

Reputation: 60062

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.

Upvotes: 7

Related Questions