complete and create magical square #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; }
C++
complete and create magical square
#include <iostream>
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;
}

Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 1 images









