按键迭代`hash_multimap`然后按值迭代

时间:2011-09-10 03:26:04

标签: c++ hashtable

我需要在密钥的所有值上执行一些代码,我需要为每个密钥重复该操作。我寻找类似的东西:

for(auto key_iterator = hash_multimap.begin_keys();
    key_iterator != hash_multimap.end_keys(); key_iterator++)
{
    auto key = key_iterator->key;
    // set up state
    for(auto value_iterator = key_iterator->begin_values();
        value_iterator != key_iterator->end_values(); value_iterator++)
    {
        // mutate state
    }
    // use state
    // tear down state
}

这当然不起作用,但有没有办法达到类似效果?问题是我需要遍历每个密钥,然后对所有密钥使用共享状态。它可以用于的例子如下:

typedef std::hash_multimap<int> hash_t;
typedef hash_t::value_type hash_val;

hash_t hash;
hash.insert(hash_val(0, 1));
hash.insert(hash_val(1, 2));
hash.insert(hash_val(1, 3));
hash.insert(hash_val(2, 4));
hash.insert(hash_val(2, 5));
hash.insert(hash_val(2, 6));
hash.insert(hash_val(3, 7));
hash.insert(hash_val(3, 8));
hash.insert(hash_val(3, 9));

// print out the sum of values for each key here.
// expected output:
//
// 0: 1
// 1: 5
// 2: 15
// 3: 24

使用hash_multimap.begin()的问题是我无法确定它是否返回该键的连续块中的每个键,即使它确实存在,我也不知道这个块的开始位置和位置结束。

编辑:我也无法使用hash_multimap.equal_range(key),因为我无法迭代密钥。迭代包含每个键只有一次的键的方法也可以解决这个问题。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用下限和上限来实现此目的。例如,尝试 -

 auto value_iterator = hash->begin();
 while( value_iterator != hash->end() ){
 {
     auto lIter = hash->lower_bound( value_iterator->first );
     auto uIter = hash->upper_bound( value_iterator->first );
     while( lIter != uIter ){
         // sum the values associated with keys
         // Increment lIter
     }
     value_iterator = uIter;
 }

编辑:如果您使用的库没有upper_bound,lower_bound成员函数,则可以使用equal_range作为@Thanatos建议。 Microsoft实现确实有这些。逻辑是相同的,内部循环是 -

pair<hash_multimap<int,int>::iterator,hash_multimap<int,int>::iterator> pairIter;
pairIter.equal_range(value_Iterator->first);
while( pairIter.first != pairIter.second ){
    // sum the values associated with keys
    // Increment pairIter->first
}
value_iterator = pairIter.second;

答案 1 :(得分:0)

由于您使用了C ++ 11语法,我也会这样做; - ]

#include <algorithm>
#include <numeric>
#include <unordered_map>
#include <iostream>

int main()
{
    typedef std::unordered_multimap<int, int> map_t;
    typedef std::unordered_map<int, int> sums_t;

    map_t hash;
    hash.insert(map_t::value_type(0, 1));
    hash.insert(map_t::value_type(1, 2));
    hash.insert(map_t::value_type(1, 3));
    hash.insert(map_t::value_type(2, 4));
    hash.insert(map_t::value_type(2, 5));
    hash.insert(map_t::value_type(2, 6));
    hash.insert(map_t::value_type(3, 7));
    hash.insert(map_t::value_type(3, 8));
    hash.insert(map_t::value_type(3, 9));

    sums_t const& sums = std::accumulate(hash.cbegin(), hash.cend(), sums_t(),
        [](sums_t& acc, map_t::const_reference p)
        {
            return acc[p.first] += p.second, acc;
        }
    );

    std::for_each(sums.cbegin(), sums.cend(),
        [](sums_t::const_reference p)
        {
            std::cout << p.first << ": " << p.second << '\n';
        }
    );
}
相关问题