基于C++11范围的循环反推迭代器.这是否意味着与boost::adaptors::indexed一起使用它是没有意义的?示例:
boost::counting_range numbers(10,20);
for(auto i : numbers | indexed(0)) {
cout << "number = " i
/* << " | index = " << i.index() */ // i is an integer!
<< "\n";
}我总是可以使用计数器,但我喜欢索引迭代器。
发布于 2016-01-21 15:23:51
在Boost 1.56 (2014年8月发布)中对此进行了修正;元素被间接地指向带有index()和value()成员函数的index()之后。
示例:http://coliru.stacked-crooked.com/a/e95bdff0a9d371ea
auto numbers = boost::counting_range(10, 20);
for (auto i : numbers | boost::adaptors::indexed())
std::cout << "number = " << i.value()
<< " | index = " << i.index() << "\n";发布于 2022-06-03 14:15:10
在迭代集合时,您可能需要索引位置(如果没有其他的话,则打印项目号),这似乎更有用:
#include <boost/range/adaptors.hpp>
std::vector<std::string> list = {"boost", "adaptors", "are", "great"};
for (auto v: list | boost::adaptors::indexed(0)) {
printf("%ld: %s\n", v.index(), v.value().c_str());
}指纹:
0: boost
1: adaptors
2: are
3: great任何简单地迭代整数范围的创新都会受到经典的for循环的强烈挑战,这仍然是非常强大的竞争对手:
for (int a = 10; a < 20; a++) 虽然这可以在许多方面被扭曲,但提出一些明显更易读的东西并不容易。
发布于 2014-08-25 18:56:27
简短的回答(正如评论中所提到的那样)是“正确的,这是没有意义的。”我也觉得这很烦人。根据您的编程风格,您可能喜欢我编写的"zipfor“包(只是标题):来自github
它允许语法类似于
std::vector v;
zipfor(x,i eachin v, icounter) {
// use x as deferenced element of x
// and i as index
}不幸的是,我无法找到一种使用基于范围的语法的方法,不得不求助于"zipfor“宏:
标题最初是为如下的事情而设计的
std::vector v,w;
zipfor(x,y eachin v,w) {
// x is element of v
// y is element of w (both iterated in parallel)
}和
std::map m;
mapfor(k,v eachin m)
// k is key and v is value of pair in m我对g++4.8进行的全面优化测试表明,生成的代码并不比手工编写代码慢。
https://stackoverflow.com/questions/16616042
复制相似问题