gpt4 book ai didi

c++ - 是否有可能在 C++ 中获得索引迭代器?

转载 作者:太空狗 更新时间:2023-10-29 20:49:33 24 4
gpt4 key购买 nike

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

python :

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

ruby / Crystal :

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++ 是否提供任何方式来表达类似的概念?

最佳答案

我不知道执行此操作的任何标准方法,但 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 .

关于c++ - 是否有可能在 C++ 中获得索引迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57947975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com