溫馨提示×

c++中怎么用sort函數進行排序

c++
小億
98
2023-10-19 11:40:28
欄目: 編程語言

在C++中,可以使用sort()函數來對數組、向量以及其他容器進行排序。以下是使用sort()函數進行排序的示例:

  1. 對數組進行排序:
#include <iostream>
#include <algorithm>
int main() {
int arr[] = {4, 2, 8, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n);
std::cout << "排序后的數組:";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}

輸出:

排序后的數組:1 2 4 5 8
  1. 對向量進行排序:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {4, 2, 8, 5, 1};
std::sort(vec.begin(), vec.end());
std::cout << "排序后的向量:";
for (int i : vec) {
std::cout << i << " ";
}
return 0;
}

輸出:

排序后的向量:1 2 4 5 8
  1. 對自定義對象進行排序:
#include <iostream>
#include <vector>
#include <algorithm>
// 定義自定義對象
struct Student {
std::string name;
int age;
double score;
};
// 自定義比較函數,按照分數從小到大排序
bool compare(const Student& s1, const Student& s2) {
return s1.score < s2.score;
}
int main() {
std::vector<Student> students = {
{"Alice", 18, 90.5},
{"Bob", 20, 85.0},
{"Charlie", 19, 92.3}
};
std::sort(students.begin(), students.end(), compare);
std::cout << "排序后的學生信息:" << std::endl;
for (const Student& s : students) {
std::cout << "姓名:" << s.name << ",年齡:" << s.age << ",分數:" << s.score << std::endl;
}
return 0;
}

輸出:

排序后的學生信息:
姓名:Bob,年齡:20,分數:85
姓名:Alice,年齡:18,分數:90.5
姓名:Charlie,年齡:19,分數:92.3

以上示例展示了如何使用sort()函數進行排序,可以根據需要自定義比較函數來實現不同的排序方式。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女