首頁  >  文章  >  後端開發  >  如何排序C++ STL容器?

如何排序C++ STL容器?

WBOY
WBOY原創
2024-06-02 20:22:00390瀏覽

C++ 中對 STL 容器排序的方法:使用 sort() 函數,原地排序容器,如 std::vector。使用有序容器 std::set 和 std::map,元素在插入時自動排序。對於自訂排序順序,可以使用自訂比較器類,例如按字母順序排序字串向量。

如何排序C++ STL容器?

如何排序C++ STL 容器

STL(標準模板庫)提供了一系列靈活且高效的通用演算法,用於對容器進行各種操作,包括排序。以下部分介紹了幾種在 C++ 中對 STL 容器進行排序的常用方法。

使用 sort() 函式

std::sort() 函式是 C++ 中進行容器排序最簡單的函式。它接受一個容器的引用或指標作為輸入,並將其元素原地排序。以下範例示範如何使用sort() 函數對一個std::vector 進行排序:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
  std::vector<int> v = {3, 1, 4, 2, 5};

  // 使用 sort() 函数对向量进行排序
  std::sort(v.begin(), v.end());

  // 打印排序后的向量
  for (int num : v) {
    std::cout << num << " ";
  }
  
  return 0;
}

輸出:##

1 2 3 4 5

使用std::set 和std::map 的內建排序

std::setstd::map 是C++ 中的有序容器,它們維護自己的元素集合併在插入時自動對元素進行排序。以下範例顯示如何使用std::set 建立和排序一組整數:

#include <iostream>
#include <set>

int main() {
  std::set<int> s = {3, 1, 4, 2, 5};

  // 由于 std::set 是有序的,元素按升序存储
  for (int num : s) {
    std::cout << num << " ";
  }
  
  return 0;
}

輸出:

1 2 3 4 5

自訂排序比較器

對於需要自訂排序順序的情況,可以透過自訂比較器類別來實現。以下範例展示如何建立自訂比較器,按字母順序對字串向量進行排序:

#include <iostream>
#include <vector>
#include <algorithm>

class StringComparator {
public:
  bool operator()(const std::string& a, const std::string& b) const {
    return a < b;
  }
};

int main() {
  std::vector<std::string> v = {"apple", "banana", "cherry", "dog", "elephant"};

  // 使用自定义比较器对向量进行排序
  std::sort(v.begin(), v.end(), StringComparator());

  // 打印排序后的向量
  for (const std::string& s : v) {
    std::cout << s << " ";
  }
  
  return 0;
}

#輸出:

apple banana cherry dog elephant

以上是如何排序C++ STL容器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn