c++中结构体排序
时间: 2025-05-23 09:14:15 浏览: 19
### C++ 结构体排序方法与实现
在 C++ 中,可以通过多种方式对结构体数组或容器中的对象进行排序。以下是几种常见的方法及其具体实现:
#### 方法 1:使用函数指针作为比较器
可以定义一个布尔类型的函数用于比较两个结构体实例,并将其传递给 `std::sort` 函数。
##### 示例代码
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
string name;
int score;
};
// 定义比较函数
bool compareByScore(const Student& a, const Student& b) {
return a.score > b.score; // 按分数降序排列
}
int main() {
vector<Student> students = {{"Alice", 85}, {"Bob", 92}, {"Charlie", 78}};
// 使用自定义比较函数进行排序
sort(students.begin(), students.end(), compareByScore);
// 输出排序结果
for (const auto& student : students) {
cout << student.name << ": " << student.score << endl;
}
return 0;
}
```
#### 方法 2:重载运算符 `<`
通过为结构体重载小于运算符 (`<`),可以直接利用默认的 `std::sort` 排序行为。
##### 示例代码
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Product {
string name;
double price;
// 重载 '<' 运算符
bool operator<(const Product& other) const {
return this->price < other.price; // 按价格升序排列
}
};
int main() {
vector<Product> products = {{"Laptop", 1200.0}, {"Smartphone", 800.0}, {"Tablet", 600.0}};
// 默认按重载的 '<' 进行排序
sort(products.begin(), products.end());
// 输出排序结果
for (const auto& product : products) {
cout << product.name << ": $" << product.price << endl;
}
return 0;
}
```
#### 方法 3:使用 lambda 表达式
Lambda 表达式是一种简洁的方式来定义匿名函数,适合简单的排序需求。
##### 示例代码
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Employee {
string name;
int age;
};
int main() {
vector<Employee> employees = {{"John", 30}, {"Jane", 25}, {"Mike", 35}};
// 使用 lambda 表达式进行排序
sort(employees.begin(), employees.end(), [](const Employee& a, const Employee& b) -> bool {
return a.age < b.age; // 按年龄升序排列
});
// 输出排序结果
for (const auto& employee : employees) {
cout << employee.name << ": " << employee.age << " years old" << endl;
}
return 0;
}
```
#### 方法 4:使用类封装比较逻辑
当需要更复杂的排序规则时,可以创建一个专门的比较类,并继承自 `std::binary_function` 或直接实现调用操作符。
##### 示例代码
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Book {
string title;
int pages;
};
class CompareBooks {
public:
bool operator()(const Book& a, const Book& b) const {
return a.pages > b.pages; // 按页数降序排列
}
};
int main() {
vector<Book> books = {{"Book A", 200}, {"Book B", 150}, {"Book C", 300}};
// 使用比较类进行排序
sort(books.begin(), books.end(), CompareBooks());
// 输出排序结果
for (const auto& book : books) {
cout << book.title << ": " << book.pages << " pages" << endl;
}
return 0;
}
```
---
以上四种方法均可满足不同场景下的结构体排序需求。每种方法各有优劣:
- **函数指针**适用于简单的情况,易于理解和维护。
- **运算符重载**使代码更加直观,但可能增加复杂度。
- **lambda 表达式**提供了极大的灵活性,尤其适合短小精悍的排序逻辑。
- **类封装**适合复杂的排序规则或多条件排序。
---
###
阅读全文
相关推荐


















