您的位置:首页 > 编程语言 > C语言/C++

C++ 预定义函数对象以及函数适配器(一)

2018-03-29 16:16 627 查看
#include<iostream>
using namespace std;

#include"functional"   //预定义函数对象的函数实现都写在这个库文件当中
#include"string"
#include<vector>
#include<list>
#include<algorithm>
#include"set"

/*总结*/
//1----->预定义函数对象基本概念:标准模板库STL提前定义了很多预定义函数对象,#include <functional> 必须包含。

//有关于plus<>预定义函数对象的正确使用  并且实现了算法与数据类型的分离 ----> 通过函数对象实现
void main21()
{
//关于参数个数,只需要追踪源码即可
plus<int> intAdd;
int a = 10;
int b = 21;
int c = intAdd(a, b);
cout << "C =" <<c<< endl;

plus<string> stringAdd;
string d = "hello";
string e = "CJLU";
string f = stringAdd(d, e);
cout << "f =" << f<<endl;

}

//有关sort中greater的使用
void main22()
{
vector<string> m_vec;

m_vec.push_back("ghello");
m_vec.push_back("dhello");
m_vec.push_back("khello");
m_vec.push_back("lhello");
m_vec.push_back("lhello");
m_vec.push_back("lhello");

for (vector<string>::iterator it = m_vec.begin(); it != m_vec.end(); it++)
{
cout << *it << " ";
}

cout << endl;

sort(m_vec.begin(), m_vec.end(), greater<string>());

for (vector<string>::iterator it = m_vec.begin(); it != m_vec.end(); it++)
{
cout << *it << " ";
}

cout << endl;

//equal_to<string>() 有两个参数,左参数来自于容器 右参数来自于sc
//函数适配器:将预定义函数对象与第二个参数进行绑定  bind2nd
string sc = "lhello";

//count_if 用来遍历容器并且返回某个元素出现的位置
int num = count_if(m_vec.begin(), m_vec.end(), bind2nd(equal_to<string>(), sc));

cout << "lhello 出现过" << num << "次";

}

int main()
{
//main21();  //有关于plus<>预定义函数对象的正确使用
main22();  //有关sort中greater的使用
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐