STL算法的使用(预定义函数及适配器)

void test1() {
	plus<int> Addint;
	int x = 10;
	int y = 20;
	int t = Addint(x, y);
	cout << "t: " << t << endl;
	plus<string> addString;
	string a = "aa";
	string b = "bb";
	string c = addString(a, b);
	cout << "c: " << c << endl;
	vector<string> vec;
	vec.push_back("a");
	vec.push_back("c");
	vec.push_back("x");
	vec.push_back("a");
	vec.push_back("b"); 
	vec.push_back("a");
	sort(vec.begin(), vec.end(), less<string>());
	for (vector<string>::iterator it = vec.begin(); it != vec.end(); it++) {
		cout << "data: " << *it << endl;
	}
	string target = "a";
	//函数适配器的初了解 equal_to<string> 有两个参数,left来自容器,right来自target
	//bin2nd函数适配器,把预定义函数对象和第二个参数进行绑定
	int num = count_if(vec.begin(), vec.end(), bind2nd( equal_to<string>(),target));

	cout << "num: " << num << endl;;

}

class IsGreat {
public:
	IsGreat(int num) {
		m_num = num;
	}
	bool operator()(int c) {
		return c > m_num;
	}
private:
	int m_num;
};

void test2() {
	vector<int> vec;
	for (int i = 0; i < 10; i++) {
		vec.push_back(i + 1);
	}
	for (vector<int>::iterator it = vec.begin(); it != vec.end(); it++) {
		cout << "data: " << *it << endl;
	}
	int num1 = count(vec.begin(), vec.end(), 3);
	cout << " num1: " << num1 << endl;
	//通过谓词求大于2的个数

	int num2 = count_if(vec.begin(), vec.end(), IsGreat(2));
	cout << "num2: " << num2 << endl;

	//通过预定义的函数对象求大于2的个数
	//greater<int>() 做参数来自容器元素,与参数设定位2
	int num3 = count_if(vec.begin(), vec.end(),  bind2nd( greater<int>(),2));
	cout << "num3: " << num3 << endl;

	//求奇数个数
	int num4 = count_if(vec.begin(), vec.end(), bind2nd(modulus<int>(), 2));
	cout << "num4: " << num4 << endl;
	//求偶数个数 取反操作
	int num5 = count_if(vec.begin(), vec.end(), not1( bind2nd(modulus<int>(), 2)));
	cout << "num5: " << num5 << endl;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值