【问题标题】:Is it possible to get an indexed iterator in C++?是否有可能在 C++ 中获得索引迭代器?
【发布时间】:2020-01-16 18:24:40
【问题描述】:

许多语言都允许对可迭代数据类型进行迭代,并在迭代时跟踪其位置。比如……

Python:

for index, value in enumerate(some_list):
    ...

红宝石/水晶:

some_list.each_with_index do |value, index|
  ...
end

生锈:

for (value, index) in some_iterable.enumerate() {
    ...
}

等等等等

根据迭代器的不同,简单地使用普通的 for 循环也可能效率低下:

for(int i = 0; i < some_list.size(); i++) {
    auto value = some_list[i];
}

C++ 有没有什么方法可以表达类似的概念?

【问题讨论】:

标签: c++ loops iteration


【解决方案1】:

我不知道这样做的任何标准方法,但 boost 提供:

#include <boost/range/adaptor/indexed.hpp>
#include <boost/assign.hpp>
#include <iterator>
#include <iostream>
#include <vector>

int main(int argc, const char* argv[])
{
    using namespace boost::assign;
    using namespace boost::adaptors;

    std::vector<int> input;
    input += 10,20,30,40,50,60,70,80,90;

    for (const auto& element : input | indexed(0))
    {
        std::cout << "Element = " << element.value()
                  << " Index = " << element.index()
                  << std::endl;
    }

    return 0;
}

本例取自from the docs

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2019-09-01
    • 2021-12-20
    • 2011-01-18
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    相关资源
    最近更新 更多