练习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;
}
}
感谢 隔壁的程序员 同学的提醒。