• 跳至主要導覽
  • 跳至主要內容
  • 跳至主要資訊欄
Office 指南

Office 指南

辦公室工作實用教學

  • Excel
  • Word
  • PowerPoint
  • Windows
  • PowerShell
  • R

C++ 程式語言 std::sort 陣列排序教學與範例

介紹如何使用 C++ 內建的排序函數來排序一般的陣列。

C++ 排序函數

若要在 C++ 程式語言中排序一般的陣列,可以直接使用 STL 標準函式庫中所提供的 sort 函數,其用法如下:

#include <iostream>

// 使用 sort 函數需要引入 algorithm 標頭檔
#include <algorithm>

using namespace std;
int main() {
  int arr[6] = {5, 3, 2, 6, 1, 4};

  // 排序 arr 陣列,需指定排序的起始與結束範圍
  sort(arr, arr + 6);

  for (int i = 0; i < 6; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
  return 0;
}

編譯並執行之後,結果為:

1 2 3 4 5 6

自訂排序函數

#include <iostream>
#include <algorithm>

using namespace std;

// 自訂比較函數
bool compare(int a, int b) {
  return a > b;
}

int main() {
  int arr[6] = {5, 3, 2, 6, 1, 4};

  // 自訂排序
  sort(arr, arr + 6, compare);

  for (int i = 0; i < 6; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
  return 0;
}

編譯並執行之後,結果為:

6 5 4 3 2 1

自動計算陣列長度

如果想要讓程式自動計算陣列長度,排序整個陣列,可以運用 sizeof 函數:

int arr[6] = {5, 3, 2, 6, 1, 4};

// 自動計算陣列長度
int len = sizeof(arr) / sizeof(int);

// 排序
sort(arr, arr + len);

排序部分元素

若要排序陣列中部份的元素(其餘保持不變),可以改變呼叫 sort 函數時所指定的排序範圍:

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
  int arr[6] = {5, 3, 2, 6, 1, 4};

  // 排序前 4 個元素
  sort(arr, arr + 4);

  for (int i = 0; i < 6; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
  return 0;
}

編譯並執行之後,結果為:

2 3 5 6 1 4

向量排序

C++ 的向量也可以使用 sort 函數來進行排序,用法大同小異:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
  vector<int> vec {5, 3, 2, 6, 1, 4};

  // 排序 vector
  sort(vec.begin(), vec.end());

  for (int i = 0; i < 6; i++) {
    cout << vec[i] << " ";
  }
  cout << endl;
  return 0;
}

編譯並執行之後,結果為:

1 2 3 4 5 6

分類:C/C++

讀者互動方式

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

主要資訊欄

搜尋

近期文章

  • C++ 語言使用 Crypto++ 實作 RSA 數位簽章教學與範例
  • C++ 語言使用 Crypto++ 實作 RSA-OAEP 搭配 SHA256 加密教學與範例
  • C++ 語言使用 Crypto++ 實作 AES 加密、解密、認證加密教學與範例
  • C++ 語言使用 Crypto++ 實作 MD5、SHA1、SHA2、BLAKE2 雜湊教學與範例
  • Ubuntu Linux 安裝、使用 Crypto++ 加密函式庫教學與範例
  • C 語言使用 OpenSSL 實作橢圓曲線 ECDH 金鑰交換教學與範例
  • Python 以 eciespy 實作 ECC 非對稱式加密方法教學與範例
  • C 語言使用 OpenSSL 實作 PBKDF2 教學與範例

推薦網站

  • Udemy 線上教學課程
  • Coursera 線上教學課程

關注本站

  • 電子郵件
  • Facebook

公益

  • 家扶基金會
  • 台灣世界展望會
  • Yahoo 奇摩公益
  • igiving 公益網
  • 兒福聯盟

Copyright © 2021 · Office Guide