我想知道是否可以交换两个大小不同的 C++ 数组的内容(不使用任何预定义的 C++ 函数)?我的代码如下:
#include <iostream>
#include <string>
using namespace std;
void swapNames(char a[], char b[])
{
//can be done with one temp; using two for clarity purposes
char* temp = new char[80];
char* temp2 = new char[80];
int x = 0;
while(*(b+x)!='\0')
{
*(temp+x) = *(b+x);
x=x+1;
}
x=0;
while(*(a+x)!='\0')
{
*(temp2+x) = *(a+x);
x=x+1;
}
x=0;
while(*(temp2+x)!='\0')
{
*(b+x) = *(temp2+x);
x=x+1;
}
x=0;
while(*(temp+x)!='\0')
{
*(a+x) = *(temp+x);
x=x+1;
}
}
int main()
{
char person1[] = "James";
char person2[] = "Sarah";
swapNames(person1, person2);
cout << endl << "Swap names..." << endl;
cout << endl << "Person1 is now called " << person1;
cout << "Person2 is now called " << person2 << endl;;
}
我最初的想法是传递对 person1 和 person2 本身的引用,将数据存储在临时变量中,删除分配给它们的内存,并将它们链接到包含交换数据的新创建的数组。我认为这可以避免预定义的内存限制。不过,似乎非常不允许将引用 (&) 传递给数组。
如果 person1 和 person2 的大小相同,上面的方法工作正常。然而,一旦我们有了不同大小的名称,我们就会遇到问题。我认为这是因为我们无法更改最初创建 person1 和 person2 时分配的内存块。
此外,是否可以在不预先定义大小的情况下在 C++ 中创建一个新数组? IE 一种创建我的临时变量而不限制其大小的方法。
最佳答案
char person1[] = "James";
只是以下内容的简写:
char person1[6] = "James";
您以后不能在 person1 中存储超过 6 个字符。如果您真正想要的是不同长度的字符串,我建议放弃 C 风格的字符串,转而使用 std::string
标准库类型:
#include <string>
#include <algorithm>
std::string person1 = "James";
std::string person2 = "Sarah";
swap(person1, person2);
如果你的书在 std::string
之前教 C 风格的字符串,你应该考虑 getting a new book .
关于c++ - 是否可以在 C++ 中交换任意大小的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12883083/