C++ 的not1与not2

一、介绍
std::not1 和 std::not2 是用来把,符合某种特殊条件的『函数对象』转换为反义「函数对象」的函数。

具体的:

not1是构造一个与谓词结果相反的一元函数对象。
not2是构造一个与谓词结果相反的二元函数对象。

二、用法
not1

// not1 example
#include <iostream>     // std::cout
#include <functional>   // std::not1
#include <algorithm>    // std::count_if
 
struct IsOdd {//是否为奇数
  bool operator() (const int& x) const {return x%2==1;}
  typedef int argument_type;
};
 
int main () {
  int values[] = {1,2,3,4,5};
  int cx = std::count_if (values, values+5, std::not1(IsOdd()));//计算不为奇数的个数
  std::cout << "There are " << cx << " elements with even values.\n";
  return 0;
}


not2

#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;

int main()
{

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; };

// 排序,不是按升序,而是按降序
std::sort(nums.begin(), nums.end(), std::not2(ascendingOrder));

for (int i : nums) {
std::cout << i << " ";
}
return 0 ;

}

 

 

posted @ 2022-03-10 22:23  小丑_jk  阅读(581)  评论(0编辑  收藏  举报