類模板
<functional>

std::unary_negate

template <class Predicate> class unary_negate;
一元求反函式物件類
一個一元函式物件類,其呼叫返回其建構函式中傳遞的另一個一元函式的相反值。

通常使用函式 not1 來構造 unary_negate 型別的物件。

該類定義為具有與以下相同的行為

1
2
3
4
5
6
7
8
9
template <class Predicate> class unary_negate
  : public unary_function <typename Predicate::argument_type,bool>
{
protected:
  Predicate fn_;
public:
  explicit unary_negate (const Predicate& pred) : fn_ (pred) {}
  bool operator() (const typename Predicate::argument_type& x) const {return !fn_(x);}
};
1
2
3
4
5
6
7
8
9
10
template <class Predicate> class unary_negate
{
protected:
  Predicate fn_;
public:
  explicit unary_negate (const Predicate& pred) : fn_ (pred) {}
  bool operator() (const typename Predicate::argument_type& x) const {return !fn_(x);}
  typedef typename Predicate::argument_type argument_type;
  typedef bool result_type;
};

模板引數

謂詞
一個一元函式物件類,具有定義的成員 argument_type

成員型別

成員型別定義說明
argument_typeT成員 operator() 中引數的型別
result_typeT成員 operator() 返回的型別

成員函式

建構函式
構造一個物件,該物件的功能呼叫返回與構造該物件時傳遞的物件相反的結果。
operator()
成員函式,返回與構造該物件時使用的函式物件相反的結果。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// unary_negate example
#include <iostream>     // std::cout
#include <functional>   // std::unary_negate
#include <algorithm>    // std::count_if

struct IsOdd_class {
  bool operator() (const int& x) const {return x%2==1;}
  typedef int argument_type;
} IsOdd_object;

int main () {
  std::unary_negate<IsOdd_class> IsEven_object (IsOdd_object);
  int values[] = {1,2,3,4,5};
  int cx;
  cx = std::count_if ( values, values+5, IsEven_object );
  std::cout << "There are " << cx << " elements with even values.\n";
  return 0;
}

輸出

There are 2 elements with even values.


另見