我搜索了其他问题,但它们似乎对我没有帮助。我需要使用迭代器遍历多重映射,但我不想遍历多重映射的每个元素,我想将迭代器增加 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/