दोनों 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";
}
नोटिस:: 'unary_function' अब मान्य नहीं है (एक लैम्ब्डा सिर्फ बेहतर है) en.cppreference.com पर उदाहरण के एक मामले में जहां
std::not1
आवश्यक है देता है। – edmzबात यह है कि, लैम्ब्डा में कोई 'argument_type' सदस्य नहीं है,' std :: not1' की आवश्यकता नहीं है। – YSC