c++字符串数组从小到大排序
时间: 2023-08-31 17:09:36 浏览: 72
可以使用标准库中的`sort`函数来对字符串数组进行排序。代码如下:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
const int N = 5;
string arr[N] = {"apple", "banana", "orange", "pear", "grape"};
sort(arr, arr + N);
for (int i = 0; i < N; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
```
输出结果为:
```
apple banana grape orange pear
```
其中,`sort(arr, arr + N)`表示对数组`arr`中前`N`个元素进行排序。由于字符串类型已经定义了相应的比较运算符,所以可以直接使用`sort`函数对字符串进行排序。
相关问题
C++按ascii码从小到大排序
可以使用标准库中的 `sort` 函数来实现,具体步骤如下:
1. 将字符串转换为字符数组,可以使用 `string` 类的 `c_str()` 成员函数或者是 `char*` 类型的数组定义。
2. 使用 `sort` 函数对字符数组进行排序,排序时传入比较函数,按照字符的 ascii 码从小到大排序。
3. 按排序后的顺序输出字符数组中的字符即可。
下面是一个示例代码:
```c++
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
bool cmp(char a, char b) {
return a < b;
}
int main() {
string s;
cin >> s;
int len = s.length();
char* arr = new char[len + 1];
strcpy(arr, s.c_str());
sort(arr, arr + len, cmp);
for (int i = 0; i < len; i++) {
cout << arr[i];
}
delete[] arr;
return 0;
}
```
注意,在使用完字符数组后需要手动释放内存,避免内存泄漏。
对字符串年月日进行从小到大排序的c++代码
以下是对字符串年月日进行从小到大排序的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DATE_LEN 11
int compare_dates(const void *a, const void *b) {
char *date1 = *(char **)a;
char *date2 = *(char **)b;
int year1, month1, day1;
int year2, month2, day2;
sscanf(date1, "%d-%d-%d", &year1, &month1, &day1);
sscanf(date2, "%d-%d-%d", &year2, &month2, &day2);
if (year1 != year2) {
return year1 - year2;
} else if (month1 != month2) {
return month1 - month2;
} else {
return day1 - day2;
}
}
int main() {
char *dates[] = {"2022-01-01", "2021-12-31", "2022-01-02", "2021-12-30"};
int num_dates = sizeof(dates) / sizeof(char *);
qsort(dates, num_dates, sizeof(char *), compare_dates);
for (int i = 0; i < num_dates; i++) {
printf("%s\n", dates[i]);
}
return 0;
}
```
这段代码使用了 `qsort` 函数来对字符串数组进行排序,排序的依据是年月日的大小关系。函数 `compare_dates` 用来比较两个日期字符串的大小,它首先将日期字符串解析成年月日三个整数,然后按照年、月、日的顺序比较它们的大小。最后,主函数中调用 `qsort` 函数对日期字符串数组进行排序,并输出排序后的结果。