|
发表于 2023-11-8 19:56:51
|
显示全部楼层
可以使用指针和using namespace std来解决这个问题。首先,我们需要使用指针来处理字符串的输入和比较。
以下是解决这个问题的C++代码:
- #include <iostream>
- #include <string>
- using namespace std;
- void sortStrings(string *strArray, int size) {
- for (int i = 0; i < size - 1; i++) {
- for (int j = 0; j < size - i - 1; j++) {
- if (strArray[j] > strArray[j + 1]) {
- string temp = strArray[j];
- strArray[j] = strArray[j + 1];
- strArray[j + 1] = temp;
- }
- }
- }
- }
- int main() {
- const int size = 3;
- string strArray[size];
- // 输入三个字符串
- for (int i = 0; i < size; i++) {
- cout << "请输入第" << i + 1 << "个字符串:";
- cin >> strArray[ i];
- }
- // 按由小到大的顺序输出
- sortStrings(strArray, size);
- cout << "按由小到大的顺序输出的字符串为:" << endl;
- for (int i = 0; i < size; i++) {
- cout << strArray[ i] << endl;
- }
- return 0;
- }
复制代码
在上面的代码中,我们首先定义了一个 sortStrings 函数,该函数使用冒泡排序算法对字符串数组进行排序。然后,在 main 函数中,我们定义了一个大小为3的字符串数组 strArray ,并使用 cin 来输入三个字符串。接下来,我们调用 sortStrings 函数对字符串数组进行排序,并使用 cout 按顺序输出排序后的字符串数组。
请注意,使用 using namespace std 可以让我们在代码中直接使用 cin 和 cout ,而无需写 std::cin 和 std::cout 。 |
|