简体   繁体   English

有效地使用 std::unordered_map 插入或增加键的值

[英]effectively use std::unordered_map to insert or increment value of a key

Given an unorder map M, a key K, an init val V. I want to set M[K] to V if K is not in M;给定一个无序 map M,一个键 K,一个初始值 V。如果 K 不在 M 中,我想将 M[K] 设置为 V; ++M[K] if K is in M. (eg use a map to count occurrence of elements) ++M[K] 如果 K 在 M 中。(例如,使用 map 来计算元素的出现次数)

There are several ways to achieve this, but when we separate find and insert/increment into two steps, at least we need hash(K) twice (How to make hints help? I think hint helps only when K is in M);有几种方法可以实现,但是当我们将 find 和 insert/increment 分成两个步骤时,至少我们需要 hash(K) 两次(如何使提示有帮助?我认为提示只有在 K 在 M 中时才有用); On the other hand, when we use member function insert_or_assign, we cannot set M[K] different according to whether K is in M.另一方面,当我们使用成员 function insert_or_assign 时,我们不能根据 K 是否在 M 中设置不同的 M[K]。

Is there a better way?有没有更好的办法?

The insert() member function returns a pair that contains an iterator and a bool; insert()成员 function 返回一个包含迭代器和布尔值的对; the iterator points either to the inserted pair or to the pair that already exists, and the bool tells you which it is (if true, a new map element was inserted; if false, the returned iterator points to something already present and the value was not changed).迭代器指向插入的对或已经存在的对,布尔值告诉你它是哪一个(如果为真,则插入一个新的 map 元素;如果为假,则返回的迭代器指向已经存在的东西,值为没有改变)。

Using this, you can put the element there if it wasn't or find it if it was there using single hash operation in all cases:使用它,您可以在所有情况下使用单个 hash 操作将元素放在那里(如果不存在)或找到它:

auto result = M.insert({ K, V });
if (!result.second) {
    // Element was already present; increment the value at the key K.
    ++(result.first->second);
}

I think I found a way to do this: try_emplace will return the iterator to M[K] when K is already in M. Then we just update M[K].我想我找到了一种方法:当 K 已经在 M 中时,try_emplace 会将迭代器返回给 M[K]。然后我们只需更新 M[K]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM