简体   繁体   English

插入std :: map的简短函数 <int, std::vector<int> &gt;

[英]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.

相关问题 在 std::map &lt; int , std::vector 中查找 vector 中元素的值<int > &gt; - Find a value of an element in vector in a std::map < int , std::vector <int >> g++:'类标准::map <int, std::vector<std::vector<int> &gt; &gt;' 没有名为 'insert_or_assign' 的成员</int,> - g++: 'class std::map<int, std::vector<std::vector<int> > >' has no member named 'insert_or_assign' 复制std :: map <int, vector<int> &gt;到std :: map <std:string, vector<int> &gt; - copy std::map<int, vector<int>> to std::map<std:string, vector<int>> 没有匹配的函数来调用&#39;merge(std :: vector <int> &,std :: vector <int> &) - No matching function for call to 'merge(std::vector<int>&, std::vector<int>&) emplace_back不使用std :: vector <std::map<int, int> &gt; - emplace_back not working with std::vector<std::map<int, int>> 如何打印 std::map <int, std::vector<int> >?</int,> - How to print std::map<int, std::vector<int>>? 没有匹配的函数调用&#39;std::map <std::pair<int, int> , int&gt;::insert(std::pair<int, int> , int)&#39; vis.insert(make_pair(1,2),3); - No matching function for call to ‘std::map<std::pair<int, int>, int>::insert(std::pair<int, int>, int)’ vis.insert(make_pair(1,2),3); 没有匹配的函数来调用&#39;std :: vector <int> ::使用宏时插入 - No matching function for call to 'std::vector<int>::insert' when using a macro 的std ::地图 <int, int> 与向量的向量 - std::map<int, int> vs. vector of vector std :: priority_queue <int, std::vector<int> ,std ::更大 <int> &gt;在min_heap函数中 - std::priority_queue<int, std::vector<int>, std::greater<int> > in min_heap function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM