Question: Complete the Vec class, void reserve( int n ), void push_back( int v ),int at( int idx ). Complete this sample code to include the
Complete the Vec class, void reserve( int n ), void push_back( int v ),int at( int idx ). Complete this sample code to include the capacity and size, this in C++
#include
using namespace std;
class Vec { public: Vec() {
} int size() { return this->sz; }
int capacity() { return this->cap; }
void reserve( int n ) { // TODO: // (0) check the n should be > size, otherwise // ignore this action. if ( n > sz ) { // (1) create a new int array which size is n // and get its address int *newarr = new int[n]; // (2) use for loop to copy the old array to the // new array
// (3) update the variable to the new address
// (4) delete old array delete[] oldarr;
}
}
void push_back( int v ) { // TODO:
if ( sz == cap ) { cap *= 2; reserve(cap); }
// complete others
}
int at( int idx ) {
}
private: int *arr; int sz = 0; int cap = 0;
};
int main() { Vec v; v.reserve(10); v.push_back(3); v.push_back(2); cout << v.size() << endl; // 2 cout << v.capacity() << endl; // 10 v.push_back(3); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(3); v.push_back(7); v.push_back(3); v.push_back(8); v.push_back(2); cout << v.size() << endl; // 11 cout << v.capacity() << endl; // 20
for ( int i = 0; i < v.size(); i++ ) { cout << v.at(i) << endl; }
return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
