C++中Sort使用的小小結

C++中Sort使用的小小結

在c++中sort的基礎用法是:

頭文件是#include <algorithm>;

sort()相對於qsort()更加靈活,對基本的類型排序不需要定義排序函數;

(1)假如數組爲arr[SIZE];

sort(arr, arr+SIZE);

輸出結果是將arr數組默認升序排列;

實際sort可以理論上讓你隨心所欲地排序(實際也不是隨心所欲)。

C++ sort的絕對值排序

我第一次想的是將每個數字的負號先記錄,再將他們的絕對值排序。

但是這表明我對sort的用法並不熟悉。因爲我在將第一個想法操作後發現,這樣較難實現。我便查閱資料,我發現可以使用調用三個參數的sort:sort(arr, arr+SIZE, compare)就成了。

我可以通過編寫compare函數改變Sort的排序規則。

比如絕對值降序排序中,就可以寫成:

bool compare(int a, int b) {

    return abs(a) > abs(b);
}

其中abs(a)代表數組中前一個數的絕對值,abs(b)代表數組後一個數的絕對值,這個函數表明數組應該按絕對值大小降序排列。

C++ sort的結構體排序

實際上這個和絕對值排序有着異曲同工之妙。

例如,結構體爲:

struct node {
  int a, b;
} mod[10];

排序規則:

bool cmp(const node& x, const node& y) { return x.b < y.b; }

運行過程和結果:

完全程序:

#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;

struct node {
  int a, b;
} mod[10];
bool cmp(const node& x, const node& y) { return x.b < y.b; }
int main(int argc, char const *argv[]) {
  for (int i = 0; i < 10; i++) {
    scanf("%d%d", &mod[i].a, &mod[i].b);
  }
  sort(mod, mod + 10, cmp);
  for (int i = 0; i < 10; i++) {
    printf("mod[%d]: %d %d\n", i, mod[i].a, mod[i].b);
  }
  return 0;
}

 

發佈了39 篇原創文章 · 獲贊 14 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章