Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}

(Sample taken from http://www.cplusplus.com/reference/algorithm/all_of)

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

Replacing foo.begin() with foo[2] does not work. I've 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 for 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++.

like image 515
Krug Avatar asked Dec 05 '25 06:12

Krug


1 Answers

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 (e.g. for the alternate it.begin() + 2); but will still be performant for the type of iterator passed to it.

like image 122
Niall Avatar answered Dec 07 '25 22:12

Niall