13873 - Dynamic Array 2   

Description

Based on the definition of Dynamic Array in Problem 13520 (nthu.edu.tw), you need to implement a dynamic array with the following functions:

  1. int& operator[](int): access data like using array. Users and main.cpp should/will not access the index which is greater or equal to size.
  2. void pushback(int x): append the element x
  3. void popback(void): pop the last element. Don't do anything if the array is empty.
  4. int back(void): return a copy of the last element. Return -1 if the array is empty.
  5. void clear(void): clear the array (set size to 0) so that the next pushbacks will place elements in data[0],data[1] and so on.
  6. int length(void): return the current size.
  7. void resize(void): double the capacity and copy the data.
  8. ~Darray(): destructor

Note that, two new functions void popback(void) and int back(void) are introduced in this problem.

// function.h

class Darray {
    public:
        Darray() {
            capacity = 100;
            size = 0;
            data = new int[capacity];
        };
        ~Darray();
        int& operator[](int);
        void pushback(int x);
        void popback(void);
        void clear(void);
        int length(void);
        int back(void);
        void print(void){
            if(this->size == 0){
                cout << endl;
            }
            else{
                for(int i=0; i<this->size; i++){
                    cout << this->data[i] << " ";
                }
                cout << endl;
            }
        };
    private:
        void resize(void); // double the capacity
        int *data;
        int capacity;
        int size;
};

Input

There are six kinds of commands:

  • “pushback integerA” represents adding an element with int value A at the end of the dynamic array.
  • “popback “ represents removing the element at the end of the dynamic array.
  • “clear” represents clearing the dynamic array.
  • “length” represents showing how many elements are in the dynamic array currently. 
  • “back” represents showing the element at the end of the dynamic array.
  • “print” represents showing the current content of the dynamic array.

Each command is followed by a new line character.

Output

The output should follow the instructions. 

("pushback", "popback" and "clear" will not print anything)

When the dynamic array is empty, you don’t need to print anything except a new line character.

Sample Input  Download

Sample Output  Download

Partial Judge Code

13873.cpp

Partial Judge Header

13873.h

Tags




Discuss