用快速排序算法写一个结构体排序 c++
时间: 2024-06-13 14:09:00 浏览: 83
以下是使用快速排序算法对结构体进行排序的C++代码示例:
```cpp
#include <iostream>
#include <vector>
using namespace std;
struct Score {
string name;
int score;
};
int partition(vector<Score>& arr, int low, int high) {
Score pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j].score < pivot.score) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quickSort(vector<Score>& arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
vector<Score> scores = {{"Alice", 80}, {"Bob", 90}, {"Charlie", 70}, {"David", 85}};
quickSort(scores, 0, scores.size() - 1);
for (auto s : scores) {
cout << s.name << " " << s.score << endl;
}
return 0;
}
```
阅读全文