2016-03-16 21 views
5

std::logical_notを使用する場合の例と、std::not1を使用する場合の例を説明してください。std :: logical_notとstd :: not1の違いは?

文書によると、前者は「単項関数オブジェクトクラス」であり、後者は「単項関数オブジェクトを構成する」ということです。ですから、今日の終わりには両方とも単項関数オブジェクトを構築します、そうではありませんか?

答えて

7

両方はファンクタ(operator()持つクラス)であるが、それらは否定ものにわずかに異なる:

  • std::logical_not<T>::operator()戻るT::operator!()。意味的には、Tを値として見て、それを否定します。
  • std::not1<T>::operator()は、!(T::operator()(T::argument_type&))を返します。意味的には、それは述語としてTを見て、それを否定する。

std::not1<T>は、より複雑な使用例の場合、std::logical_notの一般化です。


いつでもすることができます使用std::logical_notstd::logical_notとするときstd::not1

を使用する際の例を説明してください。あなたの最初のオプションが外れているときはいつでもstd::not1を使用してください。

#include <algorithm> 
#include <numeric> 
#include <iterator> 
#include <functional> 
#include <iostream> 
#include <vector> 

struct LessThan7 : std::unary_function<int, bool> 
{ 
    bool operator()(int i) const { return i < 7; } 
}; 

int main() 
{ 
    std::vector<int> v(10); 
    std::iota(begin(v), end(v), 0); 

    std::cout << std::count_if(begin(v), end(v), std::not1(LessThan7())) << "\n"; 

    //same as above, but use a lambda function 
    std::function<int(int)> less_than_9 = [](int x){ return x < 9; }; 
    std::cout << std::count_if(begin(v), end(v), std::not1(less_than_9)) << "\n"; 
} 
+0

お知らせ:: 'unary_function'が廃止されました(ラムダがちょうど良いです)en.cppreference.com上の例では、std::not1が必要な場合を提供します。 – edmz

+0

問題は、lambdaには 'argument_type'メンバーがなく、' std :: not1'がそれを必要としているということです。 – YSC

関連する問題