如何修改无序映射中的值
How to modify value in unorderedmap?
我想尝试将一个元素插入到具有键k和值v的映射中。如果该键已经存在,我想增加该键的值。
示例,
typedef std::unordered_map<std::string,int> MYMAP;
MYMAP mymap;
std::pair<MYMAP::iterator, bool> pa=
mymap.insert(MYMAP::value_type("a", 1));
if (!pa.second)
{
pa.first->second++;
}
这不起作用。我该怎么做?
您不需要迭代器来实现此目标。因为您的v
是V() + 1
,所以您可以简单地递增,而无需知道密钥是否已经存在于映射中。
mymap["a"]++;
这在你给出的例子中会很好。
unordereded_map:
一些漂亮的代码(简化了变量名):
从这里http://en.cppreference.com/w/cpp/container/unordered_map/operator_at
std::unordered_map<char, int> mu1 {{'a', 27}, {'b', 3}, {'c', 1}};
mu1['b'] = 42; // update an existing value
mu1['x'] = 9; // insert a new value
for (const auto &pair: mu1) {
std::cout << pair.first << ": " << pair.second << 'n';
}
// count the number of occurrences of each word
std::unordered_map<std::string, int> mu2;
for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence", "this", "sentence", "is", "a", "hoax"}) {
++mu2[w]; // the first call to operator[] initialized the counter with zero
}
for (const auto &pair: mu2) {
std::cout << pair.second << " occurrences of word '" << pair.first << "'n";
}
相关文章:
- 递归无序映射
- 正在将无序映射设置为无序映射的值
- 智能指针作为无序映射键,并通过引用进行比较
- 打印无序映射的第二个元素,即集合
- 由并发无序映射查找线程调用的函数是否安全?
- 如何按值对无序哈希映射进行排序
- 将大数字(10-12 位数字)存储在无序映射中<字符串,整数>
- 使用无序映射在STL中存储键值对
- 为C++中的无序映射获取给定输入键的错误值
- 将大型对象存储在无序映射中是否效率低下
- 在无序映射的结构化绑定中推导类型
- 使用无序映射进行错误索引
- 将一个向量对放在一个无序映射与一个映射中
- 如何在c++中修改无序映射中的每个值
- C++:使用一对(cpp_int,int)整数作为无序映射中的键(其中cpp_int是boost多精度整数)
- 将 [] 索引到无序映射时出现段错误
- 以std::字符串作为关键字,按字典顺序对一个无序映射进行排序
- 无序映射存储桶的节点大小
- 在无序映射<字符串上使用 find(),向量<string>>与 C++ 中的有序映射花费相同的时间
- 以三个无符号字符为关键字的无序映射