sort、qsort排序
1:qsort和sort只能对连续内存的数据进行排序,像链表map这样的结构是无法排序
2:qsort 示例
/* void qsort(void*base, // 待排序数组首地址
* size_t num, // 数组中待排序元素数量
* size_t width, // 各元素的占用空间大小
* int(__cdecl*compare)(const void*,* const void*)); // 指向函数的指针 (函数内 写明比较规则)
*/
int qsortcmp(const void *p1, const void *p2) { /* p2 > p1,return true.升序 */ /* p2 < p1,return true.逆序 */ if (strcmp((char*) p1, (char*) p2) > 0) { return 1; // 返回真时,交互位置 } return 0; } int main(int argc, char* argv[]) { fprintf(stdout, "start qsort(str1, 5, sizeof(str1[0]), qsortcmp)\n"); char str1[5][128]={"003","002","005","004","006"}; qsort(str1, 5, sizeof(str1[0]), qsortcmp); int iCnt = 0; for (iCnt = 0; iCnt < 5; ++iCnt) { fprintf(stdout, "str1[%d] is %s\n", iCnt, str1[iCnt]); } return 0; }
3:sort示例
sort默认升序排列
#include <stdio.h> #include <algorithm> int main(int argc, char* argv[]) { /*int 数组排序1*/ fprintf(stdout, "start sort(int1, int1 + 5)\n"); int int1[5] = { 3, 2, 5, 10, 9 }; int jCnt = 0; std::sort(int1, int1 + 5); // 默认升序列排列 for (jCnt = 0; jCnt < 5; ++jCnt) { fprintf(stdout, "int1[%d] is %d\n", jCnt, int1[jCnt]); } return 0; }
sort修改比较函数,降序排列
#include <stdio.h> #include <algorithm> /*int 数组排序2*/ int sortcmp1(int a, int b) { return a > b; // 降序排列 // return a < b; // 升序排列 } int main(int argc, char* argv[]) { fprintf(stdout, "start sort(int1, int1 + 5,sortcmp)\n"); int int1[5] = { 3, 2, 5, 10, 9 }; int jCnt = 0; std::sort(int1,int1+5,sortcmp1); /*sortcmp 为自己写的回调函数*/ for (jCnt = 0; jCnt < 5; ++jCnt) { fprintf(stdout, "int1[%d] is %d\n", jCnt, int1[jCnt]); } return 0; }
4:sort对map排列
/* 将map 按照 vaule 值排序输出 */
/* sort不能 直接对map排序,因此需要将map转换为vector进行排序 */
#include <stdio.h> #include <string> #include <algorithm> #include <map> #include <vector> #include <iostream> using namespace std; typedef pair <string, int> PAIR; bool sortcmp2(const PAIR& lhs, const PAIR& rhs) { return lhs.second < rhs.second; }; int main(int argc, char* argv[]) { /* 将map 按照 vaule 值排序输出 */ /* sort不能 直接对map排序,因此需要将map转换为vector进行排序 */ fprintf(stdout, "start sort map\n"); map<string, int> name_score_map; name_score_map["LiMin"] = 90; name_score_map["ZiLinMi"] = 79; name_score_map["BoB"] = 92; name_score_map.insert(make_pair("Bing", 99)); name_score_map.insert(make_pair("Albert", 86)); /* 把map中元素转存到vector中 */ vector < PAIR > name_score_vec(name_score_map.begin(), name_score_map.end()); /* 使用sort 对 vector进行排序 */ sort(name_score_vec.begin(), name_score_vec.end(), sortcmp2); /* 显示排序后的结果 */ vector<PAIR>::iterator mid = name_score_vec.begin(); for (; mid != name_score_vec.end(); ++mid) { cout << mid->first<< " " << mid->second << endl; } return 0; }