Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

These are the things I have to do to the code please help me out. Change struct to class Make all the members private Add

These are the things I have to do to the code please help me out.

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

#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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Data Mining Concepts And Techniques

Authors: Jiawei Han, Micheline Kamber, Jian Pei

3rd Edition

0123814790, 9780123814791

More Books

Students also viewed these Databases questions