2016-03-16 11 views
5

कृपया std::logical_not और std::not1 का उपयोग करने के लिए उदाहरणों के साथ समझाएं!std :: logical_not और std :: not1 के बीच अंतर?

दस्तावेज़ीकरण के अनुसार, पूर्व एक "यूनरी फ़ंक्शन ऑब्जेक्ट क्लास" है जबकि बाद वाला "एक यूनरी फ़ंक्शन ऑब्जेक्ट बनाता है"। तो दिन के अंत में दोनों एक यूनरी फ़ंक्शन ऑब्जेक्ट का निर्माण करते हैं, है ना?

उत्तर

7

दोनों functors (एक 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_not और उपयोग करने के लिए उदाहरण के साथ कृपया विस्तार से बताएं जब std::not1

उपयोग std::logical_not जब भी आप कर सकते हैं। जब भी आपका पहला विकल्प बाहर हो, 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

बात यह है कि, लैम्ब्डा में कोई 'argument_type' सदस्य नहीं है,' std :: not1' की आवश्यकता नहीं है। – YSC

संबंधित मुद्दे