【问题标题】:Convert multimap iterator to a random access iterator将多图迭代器转换为随机访问迭代器
【发布时间】:2016-03-17 18:28:07
【问题描述】:

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

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

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

【问题讨论】:

  • 您可以查看strided 的提升范围。
  • [OT]: auto 而不是 typename multimap&lt;string, int&gt;::iterator 更易读。

标签: c++ c++11 iterator


【解决方案1】:

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)))

【讨论】:

    猜你喜欢
    • 2015-02-18
    • 2015-12-04
    • 2022-11-14
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2011-05-17
    • 1970-01-01
    相关资源
    最近更新 更多