Gracos Gracos - 1 year ago 71
C++ Question

all_of function to check condition in all elements of part of an array

The following code checks if all elements in the declared array are odd numbers.

#include "stdafx.h"
#include <iostream> // std::cout
#include <algorithm> // std::all_of
#include <array> // std::array

int main () {
std::array<int,8> foo = {3,5,7,11,13,17,19,23};

if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )
std::cout << "All the elements are odd numbers.\n";

return 0;

(taken from

I would like to check if all elements in the declared array starting from foo[2] are odd numbers.

does not work. Tried many other things to make this work, all very basic (very basic C++ user here), without success. I do not want to resize the array for achieving this.

Ultimately what I'm looking for is having a loop where a condition is checked for on every element of part of an array, just as the
loop checks for a condition on any element of part of an array. This is relatively easy to achieve in R, and I'm hoping it may be equally easy to achieve in C++. Thank you.

Answer Source

You can't use an iterator and an element here, they don't represent a range. In a more general sense, even attempting to use a pointer to an element and an iterator would not be well defined for all implementations of any given container either.

You should use std::next(it.begin(), 2) to increment to the begin() iterator to the foo[2] element and then you can iterate over the range with the two iterators.

std::all_of(std::next(foo.begin(), 2), foo.end(),
  [](int i){/*...*/})

std::next() is more general and caters for iterators other than just random access iterators; but will still be performant for the type of iterator passed to it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download