[英]Is it possible to peek at the next element in a range-for loop?
Say I have this:说我有这个:
void test(std::vector<int>& my_ints) {
for (auto& my_int : my_ints) {
if (my_int == 5 && /* not the last value in the vector */) {
my_int += /* next value in the vector */;
}
}
}
Is there any valid syntax to replace the comments with?是否有任何有效的语法可以替换评论?
PS, yes, i know. PS,是的,我知道。 piece of cake with a regular for loop but I want to see if I can use range-for loops for this type of stuff.带有常规 for 循环的小菜一碟,但我想看看我是否可以将 range-for 循环用于这种类型的东西。
Is it possible to peek at the next element是否可以偷看下一个元素
In general case - no.在一般情况下 - 不。
Since objects in std::vector
are stored contiguously, you could do *(&my_int + 1)
, but if you change the container later, the code might silently break.由于std::vector
中的对象是连续存储的,您可以执行*(&my_int + 1)
,但如果您稍后更改容器,代码可能会静默中断。 Don't do that!不要那样做!
And to check if the current element is the last one, you could use &my_int == &my_ints.back()
.要检查当前元素是否是最后一个元素,您可以使用&my_int == &my_ints.back()
。
I can't think of a safe way to do what you want, with a ranged loop.我想不出一种安全的方法来做你想做的事,有一个远程循环。
If you can bare an extra helper function, you could somehow generalize the algorithm you are using, though:如果您可以提供一个额外的助手 function,您可以以某种方式概括您正在使用的算法,但是:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
template <class Container, class BinaryOp>
void apply_using_the_next(Container& cc, BinaryOp op)
{
if (std::cbegin(cc) == std::cend(cc))
return;
std::transform(std::begin(cc), std::prev(std::end(cc)),
std::next(std::cbegin(cc)),
std::begin(cc), op);
}
void test(std::vector<int>& v)
{
apply_using_the_next(v, [] (const int a, const int b) {
return a == 5 ? a + b : a;
});
}
int main()
{
std::vector<int> a{2, 5, 4, 3, 5, 5, 1};
test(a);
for (auto const i : a) // -> 2 9 4 3 10 6 1
std::cout << ' ' << i;
std::cout << '\n';
}
You can use iterator.您可以使用迭代器。
for (std::vector<int>::iterator it = my_ints.begin(); it < my_ints.end() - 1; ++it) {
if (*it == 5 /* no need to check as iterating until second last value && it != my_ints.end() - 1*/) {
*it += *(it+1);
}
}
Even if the vector is empty, the loop won't enter as it < my_ints.end() - 1 will return false, so it is safe.即使向量为空,循环也不会进入,因为它 < my_ints.end() - 1 将返回 false,因此它是安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.