结构体sort自定义排序
时间: 2023-11-02 22:02:30 浏览: 66
结构体排序中的自定义排序可以通过自定义比较函数来实现。比较函数需要返回一个bool类型的值,根据返回值来确定排序的顺序。在比较函数中,可以根据结构体中的特定成员变量来进行排序。以下是一个使用结构体sort进行自定义排序的示例代码:
```cpp
#include <algorithm>
using namespace std;
struct clever {
int x;
int y;
}a[105];
bool cmp(clever a, clever b) {
return a.y < b.y; // 以y为比较参数呈升序排列
}
int main() {
int n; // 数组大小
sort(a, a + n, cmp); // 使用自定义的比较函数进行排序
}
```
在上述代码中,cmp函数是一个自定义的比较函数,根据结构体中的y成员变量进行升序排序。在main函数中,使用sort函数对结构体数组a进行排序,排序结果将根据cmp函数的返回值确定。
相关问题
sort 自定义排序
可以使用sort()函数的第三个参数来自定义排序规则。第三个参数是一个函数,用于比较两个元素的大小。该函数应该返回一个布尔值,指示第一个参数是否小于第二个参数。如果返回true,则第一个参数排在第二个参数之前,否则第二个参数排在第一个参数之前。以下是一个自定义排序的示例:
假设我们有一个存储学生信息的结构体,包括学生的姓名和分数。我们想按照分数从高到低对学生进行排序,如果分数相同,则按照姓名的字典序从小到大排序。
```c++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Student {
string name;
int score;
};
bool cmp(const Student& a, const Student& b) {
if (a.score != b.score) {
return a.score > b.score;
} else {
return a.name < b.name;
}
}
int main() {
vector<Student> students = {{"Tom", 80}, {"Jerry", 90}, {"Alice", 70}, {"Bob", 90}};
sort(students.begin(), students.end(), cmp);
for (const auto& student : students) {
cout << student.name << " " << student.score << endl;
}
return 0;
}
```
输出结果为:
```
Jerry 90
Bob 90
Tom 80
Alice 70
```
vector的sort自定义排序
要对一个 vector 进行自定义排序,可以使用 `std::sort` 函数并提供一个自定义的比较函数作为第三个参数。比较函数应该接受两个参数,并返回一个布尔值,用于指示两个元素的顺序关系。
下面是一个示例,展示如何对一个存储了自定义结构体的 vector 进行排序:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
struct MyStruct {
int id;
std::string name;
};
bool compareById(const MyStruct& a, const MyStruct& b) {
return a.id < b.id;
}
int main() {
std::vector<MyStruct> structs = {
{3, "Charlie"},
{1, "Alice"},
{2, "Bob"}
};
std::sort(structs.begin(), structs.end(), compareById);
for (const auto& s : structs) {
std::cout << s.id << ": " << s.name << std::endl;
}
return 0;
}
```
在上面的代码中,`compareById` 函数用于比较两个 `MyStruct` 结构体对象的 `id` 字段。通过将这个函数作为第三个参数传递给 `std::sort`,我们可以根据 `id` 字段对结构体进行排序。
输出将是:
```
1: Alice
2: Bob
3: Charlie
```
你可以根据自己的需求编写不同的比较函数来实现不同的排序方式。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)