string类的字符串排序c++
时间: 2023-09-26 08:09:00 浏览: 42
可以使用`sort`函数对字符串数组排序,示例代码如下:
```c++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string arr[] = {"apple", "banana", "orange", "grape"};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
上述代码中,我们定义了一个字符串数组`arr`,然后使用`sort`函数对其进行排序。最后遍历数组并输出排序结果。需要注意的是,我们在`sort`函数中传入的第二个参数是指向数组末尾的迭代器,而不是数组长度。
相关问题
请用C++编写字符串排序--string类的使用
以下是使用string类实现字符串排序的C++代码示例:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string strs[5];
// 输入5个字符串
for (int i = 0; i < 5; i++) {
cout << "请输入第" << i+1 << "个字符串: ";
cin >> strs[i];
}
// 排序
sort(strs, strs+5);
// 输出排序后的结果
cout << "排序后的结果为:\n";
for (int i = 0; i < 5; i++) {
cout << strs[i] << endl;
}
return 0;
}
```
运行示例:
```
请输入第1个字符串: banana
请输入第2个字符串: apple
请输入第3个字符串: orange
请输入第4个字符串: pear
请输入第5个字符串: peach
排序后的结果为:
apple
banana
orange
peach
pear
```
字符串的排序C++
可以使用C++中自带的sort函数来对字符串数组进行排序。
示例代码如下:
```cpp
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string arr[] = {"orange", "apple", "banana", "grape", "pear"};
int n = sizeof(arr) / sizeof(arr[0]);
// 对字符串数组进行排序
sort(arr, arr + n);
// 输出排序后的结果
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:
```
apple banana grape orange pear
```
这里使用了C++中的string类型,string类型也可以使用sort函数进行排序。