c++ - 将多映射迭代器转换为随机访问迭代器

标签 c++ c++11 iterator

我搜索了其他问题,但它们似乎对我没有帮助。我需要使用迭代器遍历多重映射,但我不想遍历多重映射的每个元素,我想将迭代器增加 n。所以基本上是这样的:

for(typename multimap<string, int>::iterator it = words.begin(); it != words.end(); it = it + words.count(it->first))
{
    ...
}

在这种情况下,我想将迭代器增加 words.count(it->first)(这并不重要,它只是一个数字)。我知道我需要一个随机访问迭代器,但我不知道如何声明它。

最佳答案

A std::multimap有一个BidirectionalIterator并且您不能将其更改为 RandomAccessIterator .你可以做的一件事是使用 std::advance从多重映射中增加迭代器正确的数量。这是一个线性操作,但它给出了相同的语义

for(typename multimap<string, int>::iterator it = words.begin(); it != words.end(); std::advance(it, words.count(it->first)))

关于c++ - 将多映射迭代器转换为随机访问迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068841/

相关文章:

c++ - 通过 CMake 添加外部库(例如 Eigen)

c++ - 在线组装

c++ - 使用 std::unique_ptr 的具有私有(private)析构函数的单例

c++ - 为什么这需要一个显式的 std::move?

c++ - Qt Creator编译错误 "::swprintf and::vswprintf has not been declared"

c++ - 条件表达式中的右值引用

c++ - boost::filter_iterator——我将如何使用 STL 做到这一点?

c++ - C++11 中的尾端迭代器失效

java - 更换 map 中的 key ,

c++ - 如何构建 Openscenegraph earth 2.6