作用
not1是构造一个与谓词结果相反的一元函数对象。
not2是构造一个与谓词结果相反的二元函数对象。
头文件
#include <functional>
not1 例子
#include <iostream>
#include <vector>
#include <functional>
int main(int argc, char **argv)
{
std::vector<int> nums = {5, 3, 4, 9, 1, 7, 6, 2, 8};
std::function<bool(int)> less_than_5 = [](int x){ return x <= 5; };
// count numbers of integer that not less and equal than 5
std::cout << std::count_if(nums.begin(), nums.end(), std::not1(less_than_5)) << "\n";
return 0;
}
4
not2 例子
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
int main(int argc, char **argv)
{
std::vector<int> nums = {5, 3, 4, 9, 1, 7, 6, 2, 8};
std::function<bool(int, int)> ascendingOrder = [](int a, int b) { return a<b; };
// sort the nums in descending order: not ascending order
std::sort(nums.begin(), nums.end(), std::not2(ascendingOrder));
for(int i:nums) {
std::cout << i << "\t";
}
return 0;
}
9 8 7 6 5 4 3 2 1
参考资料
std::not1
https://en.cppreference.com/w/cpp/utility/functional/not1
std::not2
https://en.cppreference.com/w/cpp/utility/functional/not2
网友评论