c++ - 如何为唯一键向后迭代 multimap ?

标签 c++ iteration multimap

我知道如何向前:

for(auto it = mmap.begin(), end = mmap.end(); it != end; it = mmap.upper_bound(it->first))

但这行不通:

for(auto it = mmap.rbegin(), end = mmap.rend(); it != end; it = mmap.lower_bound(it->first))

给予: error: no match for 'operator=' in 'it = mmap.std::multimap<_Key, _Tp, _Compare, _Alloc>::lower_bound<unsigned int, long int, std::less<unsigned int>, std::allocator<std::pair<const unsigned int, long int> > >((* & it.std::reverse_iterator<_Iterator>::operator-><std::_Rb_tree_iterator<std::pair<const unsigned int, long int> > >()->std::pair<const unsigned int, long int>::first))'

最佳答案

std::multimap::iterator 不能直接转换为 std::reverse_iterator。您需要使 std::lower_bound 的结果成为 it 的基础迭代器:

typedef ... multimap_type;
typedef std::reverse_iterator<multimap_type::iterator> reverse_iterator;

for (auto it = mmap.rbegin(),
          end = mmap.rend();
     it != end;
     it = reverse_iterator(mmap.lower_bound(it->first)))
{
  // ...
}

表达式 reverse_iterator(mmap.lower_bound(it->first)) 将构造一个 std::reverse_iterator,其结果为 lower_bound作为它的基础迭代器。

关于c++ - 如何为唯一键向后迭代 multimap ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15592243/

相关文章:

c++ - (Windows HID API)HidD_GetPreparsedData() 由于句柄不正确而在 WM_INPUT 消息处理程序中失败?

c++ - 使用Qt编译测试程序时出错

ruby - "each"、 "foreach"、 "collect"和 "map"之间有什么区别?

java - java中动态创建新对象

c++ - 按计数对 multimap 进行排序

c++ - 如何将对象添加到 vector 并检查它是否有效

c++ - MPI_Type_get_extent 发生错误

c++ - 在 multimap 中为一个键找到两个最大值

javascript - 使用javascript数组创建MLM类型树结构

c++ - multimap 累积值