How to Use Binder and Bind2nd Functors in C++ STL?
Last Updated :
27 Jan, 2023
Functors in C++ (also known as function objects) are objects that can be treated as if they are functions. They can be called a function, but they can also have an internal state and can be passed around like any other object. This can be useful when you want to pass a function as an argument to another function, but you want the function to have some additional context or state.
One way to create a functor in C++ is to define a class that overloads the function call operator (operator()).
For example:
class Add {
public:
Add(int x) : x_(x) {}
int operator()(int y) { return x_ + y; }
private:
int x_;
};
This functor class, Add, takes an integer as an argument in its constructor and stores it as an internal state. It overloads the function call operator so that when an Add object is called with an integer argument, it returns the sum of its internal state and the argument.
Here’s an example of how to use this functor:
Add adder(5);
// z is now 8
int z = adder(3);
In this example, we create an Add object with an internal state of 5 and then call it with an argument of 3. The call to the adder(3) is equivalent to calling adder.operator(3), which returns the sum of 5 and 3, or 8.
Binder is a function template in the C++ Standard Template Library (STL) that allows you to create functors that bind a specific argument to a binary function. The bind2nd function template is a specific instance of binder that binds the second argument of a binary function to a specific value.
Here’s an example of how to use bind2nd to create a functor that multiplies its argument by 10:
#include <functional>
// returns 50
std::bind2nd(std::multiplies<int>(), 10)(5)
In this example, we use bind2nd to create a functor that multiplies its argument by 10. We then call this functor with an argument of 5, which returns the result of 5 * 10, or 50.
Example 1: Using a functor class to add two numbers
C++
#include <iostream>
class Add {
public :
Add( int x)
: x_(x)
{
}
int operator()( int y) { return x_ + y; }
private :
int x_;
};
int main()
{
Add adder(5);
int z = adder(3);
std::cout << "z: " << z << std::endl;
return 0;
}
|
Example 2: Using bind2nd to create a functor that multiplies its argument by 10
C++
#include <functional>
#include <iostream>
int main()
{
auto multiplier
= std::bind2nd(std::multiplies< int >(), 10);
int x = multiplier(5);
std::cout << "x: " << x << std::endl;
return 0;
}
|
Example 3: Using a binder to create a functor that subtracts a fixed value from its argument
C++
#include <functional>
#include <iostream>
int main()
{
std::binder1st<std::minus< int > > subtraction(
std::minus< int >(), 5);
int y = subtraction(10);
std::cout << "y: " << y << std::endl;
return 0;
}
|
Time Complexity: O(1).
Auxiliary Space: O(1).
Share your thoughts in the comments
Please Login to comment...