What is the easiest way to loop over the unique keys in a boost unordered_multimap.

For example I have this:

std::set<int> used;
for (auto p : valuesMap)
{
    if (used.count(p.first))
        continue;
    used.insert(p.first);

    auto range = valuesMap.equal_range(p.first);
    if (p.first)
    for (auto v = range.first; v != range.second; ++v)
        //do something;
}

Is there better way to do that. It seems like the unique keys should be already known to the unordered map.

有帮助吗?

解决方案

What you want to do is find a way to get the iterator following a certain key. In multimap I'd usually use upper_bound. But since unordered_multimap doesn't have that - I'll have to use equal_range.second:

for (auto iter=valueMap.begin();
     iter!=valueMap.end();
     iter=ValueMap.equal_range(iter->first)->second){
  uniq_key=iter->first;
  // Do whatever you want with uniq_key
}

But your example is weird to me - because you DO go over all the element . If I wanted to write your code, doing what you do, this is how I'd do it:

for (auto iter=valueMap.begin()
     iter!=valueMap.end();
     ){ // Notice the lack of ++iter!!!
  auto end=valueMap.equal_range(ier->first)->second;
  for (;iter!=end;++iter)
    // Do something
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top