I just want to get an element that is in the next iteration (using range-based for loop)
I have tried something like that:
*(&x+1) is supposed to mean "i+1" if "i" would have been an iterator here
bool factorChain(std::vector<int> arr) {
for(auto& x : arr)
{
if (*(&x+1)%x != 0) return false;
}
return true;
}
I want it to work like that, but with a range-based for loop:
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;
}
or this might be more helpful:
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;
}
*(&x+1)exhibits undefined behavior whenxrefers to the last element. With range-based loop, there's no way to stop one element short of the end.