Reputation: 4275
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
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