Arpit Jaiswal
Arpit Jaiswal

Reputation: 83

What all can be the third arguement in for_each in C++?

What all can be the third parameter in for_each in C++ ? I read its unary function but the code which I encountered had object of some class as third arguement.

Upvotes: 2

Views: 146

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

The third argument can be a function object that is an object that can be used in the postfix expression of function call.

From the C++ Standard (20.9 Function objects)

1 A function object type is an object type (3.9) that can be the type of the postfix-expression in a function call (5.2.2, 13.3.1.1).231 A function object is an object of a function object type. In the places where one would expect to pass a pointer to a function to an algorithmic template (Clause 25), the interface is specified to accept a function object. This not only makes algorithmic templates work with pointers to functions, but also enables them to work with arbitrary function objects

Here is an example

#include <iostream>
#include <algorithm>

int main()
{
    const size_t N = 10;
    int a[N] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    struct A
    {
        void operator()( int x ) const { std::cout << x << ' '; }
    };

    std::for_each( a, a + N, A() );
    std::cout << std::endl;
}    

The program output is

0 1 2 3 4 5 6 7 8 9

Here is temporary object A() of type struct A is a function object because it can be used in the postfix expression of function call due to the definition of the function call operator in struct A.

For example you can write

std::cout << A()( a[0] ) std::endl;

or

A obj;
std::cout << obj( a[0] ) std::endl;

As you see expression obj( a[0] ) looks like a function call.

Upvotes: 3

Archit Garg
Archit Garg

Reputation: 1012

From cplusplus.com :

template<class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function fn);

Parameters

first, last
Input iterators to the initial and final positions in a sequence. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.

fn
Unary function that accepts an element in the range as argument.
This can either be a function pointer or a move constructible function object.
Its return value, if any, is ignored.

Upvotes: 0

Related Questions