1 #include <algorithm> 2 #include <functional> 3 #include <array> 4 #include <iostream> 5 6 int main() 7 { 8 std::array<int, 10> s = { 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 }; 9 10 // sort using the default operator< 11 std::sort(s.begin(), s.end()); 12 for (auto a : s) { 13 std::cout << a << " "; 14 } 15 std::cout << ‘\n‘; 16 17 // sort using a standard library compare function object 18 std::sort(s.begin(), s.end(), std::greater<int>()); 19 for (auto a : s) { 20 std::cout << a << " "; 21 } 22 std::cout << ‘\n‘; 23 24 // sort using a custom function object 25 struct { 26 bool operator()(int a, int b) const 27 { 28 return a < b; 29 } 30 } customLess; 31 std::sort(s.begin(), s.end(), customLess); 32 for (auto a : s) { 33 std::cout << a << " "; 34 } 35 std::cout << ‘\n‘; 36 37 // sort using a lambda expression 38 std::sort(s.begin(), s.end(), [](int a, int b) { 39 return b < a; 40 }); 41 for (auto a : s) { 42 std::cout << a << " "; 43 } 44 std::cout << ‘\n‘; 45 }
时间: 2024-11-05 14:48:13