1. 程式人生 > 實用技巧 >C++之not1和not2

C++之not1和not2

not1是構造一個與謂詞結果相反一元函式物件not2是構造一個與謂詞結果相反二元函式物件

not1:

 1 // not1 example
 2 #include <iostream>     // std::cout
 3 #include <functional>   // std::not1
 4 #include <algorithm>    // std::count_if
 5 
 6 struct IsOdd {
 7   bool operator() (const int& x) const {return x%2==1;}
 8   typedef int
argument_type; 9 }; 10 11 int main () { 12 int values[] = {1,2,3,4,5}; 13 int cx = std::count_if (values, values+5, std::not1(IsOdd())); 14 std::cout << "There are " << cx << " elements with even values.\n"; 15 return 0; 16 }

not2:

 1 // not2 example
 2 #include <iostream>     //
std::cout 3 #include <functional> // std::not2, std::equal_to 4 #include <algorithm> // std::mismatch 5 #include <utility> // std::pair 6 7 int main () { 8 int foo[] = {10,20,30,40,50}; 9 int bar[] = {0,15,30,45,60}; 10 std::pair<int*,int*> firstmatch,firstmismatch;
11 firstmismatch = std::mismatch (foo, foo+5, bar, std::equal_to<int>()); 12 firstmatch = std::mismatch (foo, foo+5, bar, std::not2(std::equal_to<int>())); 13 std::cout << "First mismatch in bar is " << *firstmismatch.second << '\n'; 14 std::cout << "First match in bar is " << *firstmatch.second << '\n'; 15 return 0; 16 }