Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template <typename T>
- class dynamic_array {
- public:
- // Create an empty dynamic array.
- dynamic_array() {
- // Add your implementation here!
- // (You may want to use an initializer list.)
- }
- // Copy from another dynamic array instance.
- dynamic_array(const dynamic_array<T>& array) {
- // Add your implementation here!
- // (You may want to use an initializer list.)
- }
- // Assign from another dynamic array instance.
- dynamic_array<T>& operator=(const dynamic_array<T>& array) {
- // Add your implementation here!
- }
- // Destroy this array instance.
- ~dynamic_array() {
- // Add your implementation here!
- }
- // Get the current array size.
- size_t size() const {
- // Add your implementation here!
- }
- // Access an element by index.
- T& operator[](size_t index) {
- // Add your implementation here!
- }
- // Access an element by index (const overload).
- const T& operator[](size_t index) const {
- // Add your implementation here!
- }
- // Resize the array to contain 'newSize' elements.
- // If the new array size is larger fill the new slots with copies of 'value'.
- void resize(size_t newSize, const T& value = T()) {
- // Add your implementation here!
- }
- // Append element to back of array.
- void push_back(const T& element) {
- // Add your implementation here!
- }
- // Remove last element.
- void pop_back() {
- // Add your implementation here!
- }
- private:
- // Add your member variables here!
- };
- // This should work with the following use case:
- void arrayExample() {
- dynamic_array<int> array;
- // array = {}
- array.push_back(1);
- // array = { 1 }
- array.push_back(2);
- // array = { 1, 2 }
- array.pop_back();
- // array = { 1 }
- array.push_back(4);
- // array = { 1, 4 }
- array.resize(4, 100);
- // array = { 1, 4, 100, 100 }
- // Prints array contents.
- for (size_t i = 0; i < array.size(); i++) {
- printf("array[%u] = %d\n", (unsigned) i, array[i]);
- }
- // Call copy constructor for dynamic_array.
- dynamic_array<int> arrayCopy = array;
- // array = { 1, 4, 100, 100 }, arrayCopy = { 1, 4, 100, 100 }
- arrayCopy.pop_back();
- // array = { 1, 4, 100, 100 }, arrayCopy = { 1, 4, 100 }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement