练习 14.42: 使用标准库函数对象及适配器定义一条表达式,令其:
(a) 统计大于1024的值有多少个。
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
using std::placeholders::_1;
int main() {
vector<int> vec{
1, 2, 3, 4, 1088, 42, 2096, 1024
};
auto cmp = bind(greater<int>(), _1, 1024);
cout<< count_if(vec.begin(), vec.end(), cmp) << endl;
return 0;
}
(b) 找到第一个不等于pooh的字符串
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
using std::placeholders::_1;
int main() {
vector<string> vec{
"pooh", "pony", "pis",
};
auto sln = bind(not_equal_to<string>(), "pooh", _1);
vector<string>::iterator iter = find_if(vec.begin(), vec.end(), sln);
if(iter != vec.end()) {
cout<<*iter<<endl;
}
return 0;
}
(c) 将所有的值乘以2
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
using std::placeholders::_1;
int main() {
vector<int> vec{
1, 0, -1,
};
auto multi = bind(multiplies<int>(), 2, _1);
transform(vec.begin(), vec.end(), vec.begin(), multi);
for(int i : vec) {
cout<<i<<' ';
}
return 0;
}