gpt4 book ai didi

c++ - 改变数组

转载 作者:行者123 更新时间:2023-11-30 04:34:59 24 4
gpt4 key购买 nike

我在处理没有 vector 的数组时做了很多不同的事情,我想知道是否有人可以帮助我移动数组中的元素并扩展数组,同时用元素初始化新空间。我觉得我已经非常接近完成这段代码了,但是我遇到了障碍。

#include <iostream>
using namespace std;


// Function prototypes
int *reverse(int *, int);
int *expand(int *, int);
int *shift(int *, int);
void display(int[], int);
void display2(int[], int);
void display3(int[], int);


int main()
{
int const SIZE = 5;
int myArray [SIZE] = {1, 2, 3, 4, 5};
int myArray2 [SIZE] = {1, 2, 3, 4, 5};
int myArray3 [SIZE] = {1, 2, 3, 4, 5};

int *arraPtr;
int *arraPtr2;
int *arraPtr3;

arraPtr = reverse(myArray, SIZE);

display(myArray, SIZE);

arraPtr2 = expand(myArray2, SIZE);

display2(myArray2, SIZE);

arraPtr3 = shift(myArray3, SIZE);

display3(myArray3, SIZE);

delete [] arraPtr;
delete [] arraPtr2;
delete [] arraPtr3;


return 0;
}



int *reverse(int *arr, int size)
{
int *copyArray;
int posChange;

if( size < 0)
return NULL;

copyArray = new int[size];

for (int index = 0; index < --size; index++)
{
posChange = arr[index];
arr[index] = arr[size];
arr[size] = posChange;

}
return copyArray;

}


int *expand(int *arr, int size)
{
int *newArray;

newArray = new int[size * 2];
memcpy( newArray, arr, size * sizeof(int));
for (int index = size; index < (size*2); index++)
newArray[index] = 0;
return newArray;




}

int *shift(int *arr, int size)
{
int *newArray;
newArray = arr;
newArray = new int [size + 1];
for (int index = 5; index > 0; index--)
newArray[index] = newArray[index - 1];

return newArray;


}

void display(int arr[], int size)
{
for (int index = 0; index < size; index++)
{
cout << arr[index] << " ";
}

cout << endl;
}

void display2(int arr[], int size)
{
for (int index = 0; index < size; index++)
{
cout << arr[index] << " ";
}
cout << endl;

}

void display3(int arr[], int size)
{
for (int index = 0; index < size; index++)
{
cout <<arr[index] << " ";
}
cout << endl;

}

最佳答案

只有两个编译错误:int newArray;应该是 int* newArray;#include <cstring>缺少(memcpy() 所必需的)

此外,行 display(myArray, SIZE);可能是 display(arraPtr, SIZE);同样display2(myArray2, SIZE); -- 否则你只会显示原始数组,而不是函数调用的结果。

但是,这可以受益于更安全和更通用的 C++ 算法,std::copy()std::reverse_copy()至少:

int *reverse(int *arr, int size)
{
int *copyArray = new int[size];
std::reverse_copy(arr, arr+size, copyArray);
return copyArray;
}
int *expand(int *arr, int size)
{
int *newArray = new int[size * 2]();
std::copy(arr, arr+size, newArray);
return newArray;
}
int *shift(int *arr, int size)
{
int* newArray = new int [size + 1]();
std::copy(arr, arr+size, newArray+1);
return newArray;
}

完整程序:https://ideone.com/RNFiV

关于c++ - 改变数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5651898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com