對於我的任務之一我必須創建一個類來創建一個動態數組,並且具有添加或從數組中刪除數字的方法,我想出瞭如何執行add方法工作正常,但我不知道如何刪除一個元素,並減少數組的大小。從動態數組中刪除一個元素
#include <iostream>
using namespace std;
class IntegerDynamicArray
{
public:
IntegerDynamicArray()
{
currentSize = 0;
maxSize = 10;
dynamicArray = new int[maxSize];
}
int add(int x);
bool remove(int x);
private:
int* dynamicArray;
int currentSize;
int maxSize;
};
int IntegerDynamicArray::add(int x)
{
if (currentSize == maxSize)
{
maxSize = maxSize * 2;
int* tempArray = new int[maxSize];
for (int i = 0; i < currentSize; i++)
{
tempArray[i] = dynamicArray[i];
}
tempArray[currentSize] = x;
currentSize++;
dynamicArray = tempArray;
}
else
{
dynamicArray[currentSize] = x;
currentSize++;
}
return currentSize;
}
bool IntegerDynamicArray::remove(int x)
{
for (int i = 0; i < currentSize; i++)
{
if (dynamicArray[i] == x)
{
//TODO need to delete the number and move all numbers "back" by one
return true;
}
}
return false;
}
int main()
{
IntegerDynamicArray intDynArray;
while (1)
{
char input;
cout << "Enter A for add or R for remove: ";
cin >> input;
if (input == 'A')
{
cout << "Enter number to add: ";
int x;
cin >> x;
cout << intDynArray.add(x) << endl;
}
else if (input == 'R')
{
cout << "Enter number to remove: ";
int x;
cin >> x;
cout << intDynArray.remove(x) << endl;
}
}
}
你需要移動/由一個移動的所有後續元素。 – Aleph
是否要刪除數字的所有出現或僅第一次出現? –
'std :: move(iterator,iterator,iterator)' –