C++标准库bind函数中的占位符与绑定函数的参数顺序

C++标准库bind函数中的占位符与绑定函数的参数顺序,第1张

C++标准库bind函数中的占位符与绑定函数的参数顺序

定义f函数拥有5个int形参,使用bind函数绑定f函数,代码如下:

#include 
#include  //bind函数在functional头文件中
#include 

using namespace std;

int f(int a, int b, int x, int c, int y); // 声明函数
bool isShorter(char &s1, char &s2)
{
    return s1 > s2;
}

int main()
{
    string str = "Hello World";
    std::cout << str << std::endl;

    // 想要向控制台输出12345
    auto g = std::bind(f, 1, 2, std::placeholders::_2, 4, std::placeholders::_1);
    g(3, 5); // 根据g(3,5)的第一个实参与占位符_1绑定,第二个实参5与占位符_2绑定

    string words("3254617");
    sort(words.begin(), words.end(), isShorter);
    cout << words << endl;

    string words2("3254617");
    sort(words2.begin(), words2.end(), std::bind(isShorter, std::placeholders::_2, std::placeholders::_1));
    cout << words2 << endl;
}

int f(int a, int b, int x, int c, int y)
{
    cout << a << b << x << c << y << endl;
    return 0;
}

执行 g(3,5) ,发现输出如下:

得出结论:传递给g的参数按位置绑定到占位符,即,第一个参数绑定到_1,第二个参数绑定到_2。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5579204.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-14
下一篇2022-12-14

发表评论

登录后才能评论

评论列表(0条)

    保存