Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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;
- }
- }
- }
- bool IntegerDynamicArray::remove(int x)
- {
- for (int i = 0; i < currentSize; i++)
- {
- if (dynamicArray[i] == x)
- {
- for ( ; i < currentSize - 1; i++)
- {
- // Assign the next element to current location.
- dynamicArray[i] = dynamicArray[i + 1];
- }
- // Remove the last element as it has been moved to previous index.
- dynamicArray[currentSize - 1] = 0;
- currentSize = currentSize - 1;
- return true;
- }
- }
- return false;
- }
- bool IntegerDynamicArray::remove(int x)
- {
- for (int i = 0; i < currentSize; i++)
- {
- if (dynamicArray[i] == x)
- {
- int *newArray = new int[currentSize-1];
- std::copy(dynamicArray, dynamicArray+i, newArray);
- std::copy(dynamicArray+i+1, dynamicArray+currentSize, newArray+i);
- delete[] dynamicArray;
- dynamicArray = newArray;
- --currentSize;
- return true;
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement