试建立一个类string实现将两个成员数组中的字符串连接成一个并将连接后的字符串按升序排列存入数组三
时间: 2024-03-02 17:48:36 浏览: 34
好的,我理解了你的要求。以下是一个简单的实现:
```
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX_LEN = 100;
class MyString {
private:
char str[MAX_LEN];
public:
MyString(const char* s = "") {
strcpy(str, s);
}
const char* c_str() const {
return str;
}
bool operator < (const MyString& other) const {
return strcmp(str, other.str) < 0;
}
};
int main() {
MyString arr1[] = {"hello", "world", "foo", "bar"};
MyString arr2[] = {"apple", "orange", "banana"};
int len1 = sizeof(arr1) / sizeof(MyString);
int len2 = sizeof(arr2) / sizeof(MyString);
int len3 = len1 + len2;
MyString arr3[len3];
int idx = 0;
for (int i = 0; i < len1; i++) {
arr3[idx++] = arr1[i];
}
for (int i = 0; i < len2; i++) {
arr3[idx++] = arr2[i];
}
sort(arr3, arr3 + len3);
for (int i = 0; i < len3; i++) {
cout << arr3[i].c_str() << " ";
}
cout << endl;
return 0;
}
```
这个实现中,我们定义了一个名为`MyString`的类,它有一个成员变量`str`,表示字符串的内容。这个类还有一个`c_str()`方法,返回一个指向字符串内容的指针。我们在这个类中重载了`<`运算符,以便能够使用`sort()`函数对这个类的对象排序。
在`main()`函数中,我们定义了两个`MyString`类型的数组`arr1`和`arr2`,并将它们的元素合并到了一个数组`arr3`中。我们使用`sort()`函数对`arr3`进行排序,并输出排序后的结果。
需要注意的是,这个实现中的字符串长度是有限制的,如果字符串太长可能会导致数组越界或者内存溢出。在实际应用中,我们可能需要使用动态内存分配来避免这个问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)