sort函数比较string类型
时间: 2023-08-03 18:37:36 浏览: 69
在C++中,可以使用sort函数对数组或容器中的元素进行排序。对于string类型,可以直接使用sort函数进行排序。sort函数默认按照字典序进行排序,也可以通过自定义比较函数来指定排序规则。
以下是一个使用sort函数对string数组进行排序的示例代码:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string arr[] = {"apple", "banana", "orange", "pear"};
int n = sizeof(arr) / sizeof(string);
// 按照字典序升序排序
sort(arr, arr + n);
// 输出排序结果
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
apple banana orange pear
```
在这个示例中,sort函数默认按照字典序进行排序,即按照首字母的ASCII码值进行排序。
相关问题
string 类型可以使用sort函数么
可以使用sort函数,但是需要自定义比较函数。因为sort默认是按照ASCII码排序的,如果想按照其他规则排序就需要自定义比较函数。例如:
```cpp
bool comp(string a, string b) {
return a.length() < b.length();
}
```
这个比较函数按照字符串长度从小到大排序。然后在sort函数中传入这个比较函数即可:
```cpp
sort(strVec.begin(), strVec.end(), comp);
```
sort函数比较结构体
可以使用sort函数比较结构体。在使用sort函数时,可以自定义比较函数,来指定结构体的排序方式。比较函数需要传入两个参数,通常为const引用类型,分别为要比较的结构体的两个实例。比较函数需要返回一个bool类型的值,来表示两个结构体的大小关系。例如,比较两个Person结构体的年龄大小,可以如下定义比较函数:
```
struct Person {
string name;
int age;
};
bool cmp(const Person& a, const Person& b) {
return a.age < b.age;
}
int main() {
vector<Person> people = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 20}};
sort(people.begin(), people.end(), cmp);
for (const auto& person : people) {
cout << person.name << " " << person.age << endl;
}
return 0;
}
```
在上述代码中,我们定义了一个Person结构体,包含姓名和年龄两个成员;然后定义了一个比较函数cmp,按照年龄从小到大排序;最后使用sort函数对people数组进行排序,并输出排序结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)