利用c++语言和指针再次编写上述问题
时间: 2024-03-18 18:39:00 浏览: 68
好的,这是一个C++版本的程序,使用指针和标准库函数实现:
```cpp
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX_SONG_NUM = 10;
const int MAX_SONG_NAME_LEN = 50;
int main()
{
char song_names[MAX_SONG_NUM][MAX_SONG_NAME_LEN]; // 存放歌名的二维字符数组
char *song_ptrs[MAX_SONG_NUM]; // 存放歌名指针的一维字符指针数组
// 输入10首歌名并存入song_names数组中
cout << "Please enter 10 song names:" << endl;
for (int i = 0; i < MAX_SONG_NUM; i++) {
cin >> song_names[i];
}
// 将song_ptrs数组中的元素指向song_names数组中每个字符串的首地址
for (int i = 0; i < MAX_SONG_NUM; i++) {
song_ptrs[i] = song_names[i];
}
// 使用标准库函数sort对歌名进行排序
sort(song_ptrs, song_ptrs + MAX_SONG_NUM, [](const char *a, const char *b){
return strcmp(a, b) < 0;
});
// 输出排序后的歌名
cout << "The sorted song names are:" << endl;
for (int i = 0; i < MAX_SONG_NUM; i++) {
cout << song_ptrs[i] << endl;
}
return 0;
}
```
这个程序和C语言版本的程序类似,主要区别在于使用了 `iostream` 和标准库函数 `sort`。我们使用 `cin` 和 `cout` 进行输入输出,使用 `sort` 函数对指针数组进行排序,并使用了lambda表达式作为比较函数。
阅读全文
相关推荐








