c++ - 是否可以在 C++ 中交换任意大小的数组?

标签 c++ arrays

我想知道是否可以交换两个大小不同的 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/

相关文章:

c - 使用数组的平均分数 - 由用户在一定时间内输入

c - 如何只从字符串中提取数字?

c++ - Linux:作为共享对象 API 的 C++ 抽象类

c - 为什么我的合并函数输出一个无序的数组?

c++ - std::set 没有前后成员函数是否有设计原因?

C++ Qt程序设计问题

python - 将数组转换为 MultiLabelBinarizer 的列表

php - 如何更改数组中每个键的第一个字符?

c++ - SizeOfImage 成员导致程序崩溃

c++ - 将reinterpret_cast 转换为较小的数组是否安全?有更好的选择吗?