我在處理沒有矢量的數組時做了很多不同的操作,我想知道是否有人可以幫助我在數組中移動元素並在用元素初始化新空間時擴展數組。我覺得我很接近完成這個代碼,但是我打了一個塊。更改陣列
#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;
}
它看起來像你的newArray變量裏面的shift應該是一個int指針,但考慮到你實際上並沒有在其他代碼中使用shift,它可能並不重要。你可能應該更新它。 – 2011-04-13 15:49:22
究竟是什麼問題?你有任何錯誤?什麼不按預期工作?它以哪種方式不按預期工作? – sth 2011-04-13 15:49:22