sort属于C++范畴,在algorithm头文件中,下面直奔主题,给大家一个清晰明了的认识.qsort有C,和C++两个版本.
qsort的compare函数原型 //comp ,也就说,如果the first < the second 返回-1,;如果the first > the second 返回1;如果the first == the second 返回0.,排序结果就表现为升序
comp | - | comparison function which returns a negative integer value if the first argument is less than the second, a positive integer value if the first argument is greater than the second and zero if the arguments are equal. int cmp(const void *a, const void *b); The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array. |
1 #include <algorithm> 2 #include <functional> 3 #include <array> 4 #include <iostream> 5 #include <limits.h> 6 using namespace std; 7 int cmpself(const void *a, const void *b){ 8 int arg1 = *static_cast<const int*>(a); 9 int arg2 = *static_cast<const int*>(b); 10 11 if(arg1 < arg2) return -1; 12 if(arg1 > arg2) return 1; 13 return 0; 14 //return arg1 < arg2;//如果将上面的改为这个呢?降序排列 15 //return arg1 > arg2;//升序 16 } 17 int main() 18 { 19 //C++ sort 排序规则:前面元素大于后面元素,就返回降序结果;否则,返回升序结果. 20 std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; 21 22 // sort using the default operator< sort默认升序排列 23 std::sort(s.begin(), s.end()); 24 for (auto a : s) { 25 std::cout << a << " "; 26 } 27 std::cout << ' '; 28 29 // sort using a standard library compare function object 30 //the former is greater than the later,降序排列 31 std::sort(s.begin(), s.end(), std::greater<int>()); 32 for (auto a : s) { 33 std::cout << a << " "; 34 } 35 std::cout << ' '; 36 37 // sort using a custom function object 38 struct { 39 bool operator()(int a, int b) 40 { 41 return a < b;//升序排列 42 } 43 } customLess; 44 std::sort(s.begin(), s.end(), customLess); 45 for (auto a : s) { 46 std::cout << a << " "; 47 } 48 std::cout << ' '; 49 50 // sort using a lambda expression 51 std::sort(s.begin(), s.end(), [](int a, int b) { 52 return b < a; //降序排列 53 }); 54 for (auto a : s) { 55 std::cout << a << " "; 56 } 57 std::cout << ' '; 58 59 //c++ qsort 60 int arr[] = {-2, 99, 0, -743, 2, INT_MIN+1, 4}; 61 constexpr std::size_t elesize = sizeof(arr[0]); 62 constexpr std::size_t size = sizeof(arr) / sizeof(arr[0]); 63 64 std::qsort(arr, size, sizeof(arr[0]), [](const void* a, const void* b) 65 { 66 int arg1 = *static_cast<const int*>(a); 67 int arg2 = *static_cast<const int*>(b); 68 //return arg1 < arg2; //error 69 if(arg1 < arg2) return -1; 70 if(arg1 > arg2) return 1;//需要注意的是,无论是C还是C++中的qsort, 71 return 0; 72 73 // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut 74 // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) 75 }); 76 77 for(int ai : arr) 78 std::cout << ai << ' '; 79 std::cout << ' '; 80 std::qsort(arr, size, sizeof(arr[0]), cmpself); 81 for(int ai : arr) 82 std::cout << ai << ' '; 83 std::cout << ' '; 84 }