Question: The one that was previously posted on here does not compile or function as intended. Change struct to class Make all the members private Add

The one that was previously posted on here does not compile or function as intended.

Change struct to class

Make all the members private

Add get_size , get_capacity and get_array methods

Add remove, index_of and operator+ methods

Add oprator< method, and together with other five ( > , >= , <= , == , != )

Complete and debug all the other methods in the sample code, such as insert

Write some testing code in the main function Code template:

#include using namespace std;

struct Vec { int _size; int _cap; int* arr;

Vec() { _size = 0; _cap = 4; arr = new int[_cap]; }

void insert( int n, int x ) { for ( int i = _size-1; i >= n; i-- ) { arr[i+1] = arr[i]; } arr[n] = x; _size++; }

void reserve( int new_cap ) { if ( new_cap > _cap ) { _cap = new_cap; int *tmp = new int[_cap]; for ( int i = 0; i < _size; i++ ) { tmp[i] = arr[i]; } delete[] arr; arr = tmp; } }

void push_back( int x ) { if ( _size == _cap ) { _cap *= 2; reserve(_cap); } arr[_size++] = x; }

void pop() { if (_size > 0) _size--; }

int& at( int idx ) { if ( idx >= _size || idx < 0 ) { throw "[Vector] Index out of bound!"; } return arr[idx]; }

int& operator[]( int idx ) { if ( idx >= _size || idx < 0 ) { throw "[Vector] Index out of bound!"; } return arr[idx]; }

~Vec() { delete[] arr; }

};

ostream& operator<<(ostream& os, Vec& v) { os << "[ "; for ( int i = 0; i < v._size-1; i++ ) { os << v.arr[i] << ", "; } os << v.arr[v._size-1] << " ]"; return os; }

int main() { Vec v; v.push_back(3); v.push_back(1); v.push_back(4); v.push_back(2); v.push_back(8); //v.insert(1, 7); v[3] = 5; cout << v[3] << endl; //v.at(3) = 5; cout << v << endl; //cout << v._cap << endl; //v.reserve(20); //cout << v._cap << endl; //cout << v << endl; //cout << v._size << endl; //cout << v._cap << endl; return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!