c++中comparator的其他函数
时间: 2024-03-13 18:45:51 浏览: 20
在 C++ 中,`comparator` 通常是一个函数指针,用于比较两个元素的大小。在 `sort` 函数中,可以自定义 `comparator` 函数,来实现按照不同的顺序进行排序。
除了常见的升序和降序排序,还有其他一些比较常用的比较函数,如下所示:
1. 按照字符串长度排序
```cpp
bool cmp(string a, string b) {
return a.length() < b.length();
}
```
2. 按照字符串字典序排序
```cpp
bool cmp(string a, string b) {
return a < b;
}
```
3. 按照字符串字典序的反向排序
```cpp
bool cmp(string a, string b) {
return a > b;
}
```
4. 按照结构体的某个成员变量排序
```cpp
struct Student {
string name;
int age;
};
bool cmp(Student a, Student b) {
return a.age < b.age;
}
```
5. 按照结构体的多个成员变量排序
```cpp
struct Student {
string name;
int age;
int score;
};
bool cmp(Student a, Student b) {
if (a.score != b.score) {
return a.score > b.score; // 按照分数降序排序
} else if (a.age != b.age) {
return a.age < b.age; // 如果分数相同,按照年龄升序排序
} else {
return a.name < b.name; // 如果分数和年龄都相同,按照姓名字典序排序
}
}
```
在自定义比较函数时,需要注意函数的返回值必须是 `bool` 类型,表示两个元素的大小关系。如果返回值为 `true`,则表示第一个元素比第二个元素小(或者说应该排在前面),否则返回 `false`。