编写一个自定义函数 sort,完成对 n 个字符串的降序排序,然后在 main 函数 中调用 sort,对“Beijing”,“Shanghai”,“Shenzhen”、“Nanjing”、“Dalian”、“Qingdao” 6 个字符串排序,要求用指针数组表示这 6 个字符串
时间: 2023-10-09 16:16:24 浏览: 77
好的,我知道了。下面是代码实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void sort(string **str, int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (*str[i] < *str[j]) {
string *temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
int main() {
string *str[6];
str[0] = new string("Beijing");
str[1] = new string("Shanghai");
str[2] = new string("Shenzhen");
str[3] = new string("Nanjing");
str[4] = new string("Dalian");
str[5] = new string("Qingdao");
sort(str, 6);
for (int i = 0; i < 6; i++) {
cout << *str[i] << endl;
delete str[i];
}
return 0;
}
```
在 sort 函数中,我们使用选择排序的思想,对指针数组中的字符串进行降序排序。在 main 函数中,我们先创建了一个指针数组,用于存储 6 个字符串的地址。然后调用 sort 函数进行排序。最后输出排序后的字符串,并释放内存。
注意,在 sort 函数中,我们使用的是双重指针,这是因为我们需要修改指针数组中的指针的值,而不是字符串的值。如果使用单重指针,则无法完成排序。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)