gpt4 book ai didi

c++ - 如何更改(向前/向后移动)基于范围的 for 循环中的迭代器?

转载 作者:太空宇宙 更新时间:2023-11-04 15:56:09 27 4
gpt4 key购买 nike

我只想获取下一次迭代中的元素(使用基于范围的 for 循环)

我试过类似的东西:

*(&x+1) 应该表示“i+1”,如果“i”在这里是一个迭代器的话

bool factorChain(std::vector<int> arr) {
for(auto& x : arr)
{
if (*(&x+1)%x != 0) return false;
}
return true;
}

我希望它像那样工作,但使用基于范围的 for 循环:

bool factorChain(std::vector<int> arr) {
for(int i=0; i<arr.size()-1; i++)
{
if(arr[i+1]%arr[i]!=0) return false;
}
return true;
}

或者这可能更有帮助:

bool factorChain(std::vector<int> arr) {
for(std::vector<int>::const_iterator iter = arr.begin();
iter != arr.end()-1; ++iter){
if(*(iter+1)%*(iter)!=0) return false;
}
return true;
}

最佳答案

如果你真的一心想使用基于范围的循环,你可以这样做:

bool factorChain(std::vector<int> arr) {
int* prev = nullptr;
for(auto& x : arr)
{
if (prev && x % *prev != 0) return false;
prev = &x;
}
return true;
}

但是,在这一点上,仅拼出一个基于迭代器或基于索引的循环可能比尝试挽救基于范围的循环更清晰、更具可读性。


现在,对于额外的微妙点,像这样的东西怎么样:

bool factorChain(std::vector<int> arr) {
return std::adjacent_find(arr.begin(), arr.end(),
[](int prev, int next) { return next % prev != 0; })
== arr.end();
}

关于c++ - 如何更改(向前/向后移动)基于范围的 for 循环中的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57367443/

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