STL中的内建函数对象(一看就懂)

什么是内建函数对象

答: STL提供的仿函数

STL内建了一些函数对象。分为:算数类函数对象,关系运算类函数对象,逻辑运算 类仿函数。这些仿函数所产生的对象,用法和一般函数完全相同,当然我们还可以 产生无名的临时对象来履行函数功能。使用内建函数对象,需要引入头文件

6个算数类函数对象,除了negate是一元运算,其他都是二元运算。 
template<class T> T plus<T>// 加 法 仿 函 数 
template<class T> T minus<T>// 减 法 仿 函 数 
template<class T> T multiplies<T>// 乘 法 仿 函 数 
template<class T> T divides<T>// 除 法 仿 函 数 
template<class T> T modulus<T>// 取 模 仿 函 数 
template<class T> T negate<T>// 取 反 仿 函 数 
6个关系运算类函数对象,每一种都是二元运算。 
template<class T> bool equal_to<T>// 等 于 
template<class T> bool not_equal_to<T>// 不 等 于 
template<class T> bool greater<T>// 大 于 
template<class T> bool greater_equal<T>// 大 于 等 于 
template<class T> bool less<T>// 小 于 
template<class T> bool less_equal<T>// 小 于 等 于 
逻辑运算类运算函数,not为一元运算,其余为二元运算。 
template<class T> bool logical_and<T>// 逻 辑 与 
template<class T> bool logical_or<T>// 逻 辑 或 
template<class T> bool logical_not<T>// 逻 辑 非

案例(加法仿函数)

// 加 法 仿 函 数 
void test02() 
{ 
	plus<int> p; 
	cout << p(10, 20) << endl;			//30
	cout<<plus<int>()(100,300)<<endl;	//300
}

案例二(使用内建函数对象 改变排序规则)

//使用内建函数对象 改变排序规则
void test04()
{
    vector<int> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    v.push_back(40);
    v.push_back(50);

    for_each(v.begin(),v.end(),[](int val){cout<<val<<" ";});
    cout<<endl;

    //使用内建函数对象 改变排序规则
    sort(v.begin(),v.end(), greater<int>() );
    
    for_each(v.begin(),v.end(),[](int val){cout<<val<<" ";});
    cout<<endl;
}

运行结果:
在这里插入图片描述

发布了78 篇原创文章 · 获赞 45 · 访问量 9261

猜你喜欢

转载自blog.csdn.net/weixin_43288201/article/details/105258866