解释一下代码?

Akr*_*and -2 c++ bind2nd

我遇到了这段代码.从输出时,除以2,但语法不熟悉我,我可以推断,其余阵列存储阵列数量的剩余部分.

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

}
Run Code Online (Sandbox Code Playgroud)

变换和bind2nd在这种情况下做了什么?我阅读了文档,但我不清楚.

Mil*_*nek 5

std::bind2nd是一个旧函数,用于将值绑定到函数的第二个参数.它已被std::bindlambdas 取代.

std::bind2nd 返回一个可调用对象,它有一个参数并调用与该参数作为第一个参数,并且结合的参数作为其第二个参数被包装的可调用:

int foo(int a, int b)
{
    std::cout << a << ' ' << b;
}

int main()
{
    auto bound = std::bind2nd(foo, 42);
    bound(10); // prints "10 42"
}
Run Code Online (Sandbox Code Playgroud)

std::bind2nd(及其合作伙伴std::bind1st)在C++ 11中被弃用,在C++中删除17.它们在C++ 11中被更灵活的std::bind以及lambda表达式替换:

int foo(int a, int b)
{
    std::cout << a << ' ' << b;
}

int main()
{
    auto bound = std::bind(foo, std::placeholders::_1, 42);
    bound(10); // prints "10 42", just like the std::bind2nd example above

    auto lambda = [](int a) { foo(a, 42); };
    lambda(10); // prints "10 42", same as the other examples
}
Run Code Online (Sandbox Code Playgroud)

std::transform 在一个范围的每个元素上调用一个callable,并将调用的结果存储到输出范围中.

int doubleIt(int i)
{
    return i * 2;
}

int main()
{
    int numbers[] = { 1, 2, 3 };
    int doubled[3];

    std::transform(numbers, numbers + 3, doubled, doubleIt);
    // doubled now contains { 2, 4, 6 }
}
Run Code Online (Sandbox Code Playgroud)