Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use of all_of function in C++

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 116
    Comment on it

    all_of function is used to test condition on all the elements in a range[first,last), it will return true if the test condition is true for each and every element in the range or if the range is empty, else it will return false.

    Function Prototype

    bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);
    

    About the parameters

    first

    It is the initial position of the range which is included in the range.


    last

    It is the last position in the range, which is not included in the range.

    pred

    It is a unary function which return value which is convertible to bool. This function is used to test condition on the elements in the range.

    Sample program using all_of

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
            int arr_one[] = {2,4,6,8,10};
            int arr_two[] = {2,3,6,8,10};
    
            if ( all_of(arr_one,arr_one+5,[](int i){return !(i%2);})) {
                    cout << "All the elements in the range are even.\n";
            } else {
                    cout << "All the elements in the range are not even.\n";
            }
    
            if ( all_of(arr_two,arr_two+5,[](int i){return !(i%2);})) {
                    cout << "All the elements in the range are even.\n";
            } else {
                    cout << "All the elements in the range are not even.\n";
            }
    
            return 0;
    }
    

    Output of the program

    All the elements in the range are even.
    All the elements in the range are not even.
    

    The complexity of all_of function is upto linear

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: