第十四章 14.8.2节练习

练习14.42

使用标准库函数对象及适配器定义一条表达式,令其

(a) 统计大于1024的值有多少个

(b) 找到第一个不等于pooh的字符串

(c) 将所有的值乘以2

解答:

#include <iostream>
#include <functional>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
	// (a)
	vector<int> number { 10, 100, 1000, 10000, 1000000, 1000000, 9000 };
	int lager1024 = count_if(number.cbegin(), number.cend(), bind2nd(greater<int>(), 1024));
	cout << lager1024 << endl;
	// (b)
	vector<string> str{ "pooh", "two", "three" };
	auto it = find_if(str.cbegin(), str.cend(), bind1st(not_equal_to<string>(), "pooh"));
	cout << *it << endl;
	// (c)
	vector<int> number2 = number;
	transform(number.begin(), number.end(), number2.begin(), bind2nd(multiplies<int>(), 2));
	for (auto i : number2){
		cout << i << endl;
	}
}

练习14.43

使用个标准库函数对象判定一个给定的int值是否能被int容器中的所有元素整除。

解答:

#include <iostream>
#include <functional>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
	vector<int> num{ 738, 493, 403, 485, 74, 4793, 4950 }, result = num;
	transform(num.begin(), num.end(), result.begin(), bind2nd(modulus<int>(), 26));
	/*
	for (auto i : result){
		cout << i << endl;
	}
	*/
	<span style="line-height: 20px;">if (count(result.begin(), result.end(), 0) == result.size())</span>{
		cout << "this array can be divide by 26" << endl;
	}
	else {
		cout << "this array can not be divide by 26" << endl;
	}
}

感谢 隔壁的程序员 同学的提醒。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值