I came across this code. From the output I could infer that remainder array stores the remainder of numbers array when divided by 2. But the syntax is unfamiliar to me.
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
int main ( )
{
int numbers[ ] = {1, 2, 3};
int remainders[3];
transform ( numbers, numbers + 3, remainders, bind2nd(modulus<int>( ), 2) );
for (int i = 0; i < 3; i++)
{
cout << (remainders[i] == 1 ? "odd" : "even") << "\n";
}
return 0;
}
What do transform and bind2nd do in this context? I read the documentation but it was not clear to me.
std::bind2ndis an old function for binding a value to the second parameter of a function. It has been replaced bystd::bindand lambdas.std::bind2ndreturns a callable object that takes one parameter and calls the wrapped callable with that parameter as its first parameter and the bound parameter as its second parameter:std::bind2nd(and its partnerstd::bind1st) were deprecated in C++11 and removed in C++17. They were replaced in C++11 by the more flexiblestd::bindas well as lambda expressions:std::transformcalls a callable on each element of a range and stores the result of the call into the output range.