栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/588003.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号