1、sort簡介
- sort函數包含在頭文件
<algorithm>
中- sort函數使用之前,需要通過
#include <algorithm>
引入- sort函數使用的是快速排列或類似快速排列的改進算法,時間復雜度一般為O(nlog(n))
2、sort用法
2.1 基礎用法
#include <iostream>
#include <algorithm> // 包含sort函數int main() {int arr[] = {5, 7, 1, -2, 4, 9};int n = sizeof(arr)/sizeof(arr[0]);std::sort(arr, arr + n); // 對整個數組進行升序排序for(int i = 0; i < n; ++i) {std::cout << arr[i] << " ";}return 0;
}
2.2 自定義比較函數
#include <iostream>
#include <algorithm>bool compare(int a, int b) {return a > b; // 降序排序
}int main() {int arr[] = {5, 7, 1, -2, 4, 9};int n = sizeof(arr)/sizeof(arr[0]);std::sort(arr, arr + n, compare); // 使用自定義比較函數進行排序for(int i = 0; i < n; ++i) {std::cout << arr[i] << " ";}return 0;
}
2.3 Lambda表達式
#include <iostream>
#include <algorithm>
#include <array>struct Person {std::string name;int age;
};int main() {std::array<Person, 3> people = {Person{"Alice", 30},Person{"Bob", 25},Person{"Charlie", 35}};std::sort(people.begin(), people.end(), [](const Person &a, const Person &b) -> bool {return a.age < b.age; // 根據年齡升序排序});for(const auto &person : people) {std::cout << person.name << " (" << person.age << ")\n";}return 0;
}
微語錄:成功的秘訣在于堅持不懈奮斗與不斷學習新知。無論前方的道路多么崎嶇不平,勇于追夢的腳步不應停歇。