[英]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? 编写这个插入函数是否有一种不那么冗长的方式(在C ++ 11中)?
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. 我不认为你的函数特别冗长,但在这种情况下它可以简单地用dict[key].push_back(val)
代替,因为map上的operator[]
默认构造值,如果它不存在的话。 You don't need the if
block. 你不需要if
块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.