Define the ADT IVector for the management of a dynamic vectorof integers. The cl
ID: 3611099 • Letter: D
Question
Define the ADT IVector for the management of a dynamic vectorof integers. The class overload the subscript operator [] and incase of writing or reading out side of the vector range the classIVector throws an handling exception. Develop also a simple testingprogram.!!!!DONT NEED THE TOP PORTION!!!! Repeat the previous problem for a generic type INC++ Define the ADT IVector for the management of a dynamic vectorof integers. The class overload the subscript operator [] and incase of writing or reading out side of the vector range the classIVector throws an handling exception. Develop also a simple testingprogram.
!!!!DONT NEED THE TOP PORTION!!!! Repeat the previous problem for a generic type INC++
Explanation / Answer
private:
int *buf;
int sz;
int in_range(int i);
protected:
int &elem(int i);
public:
Vector(int size);
Vector(Vector &v);
~Vector();
int size();
int &operator [](int i);
Vector &operator =(Vector &v);
Vector :: Vector(intsize) :
sz(size),
buf(new int[size])
{
while (--size >= 0)
buf[size] = 0;
}
// destructors should deallocate dataallocated by the constructor
Vector ::~Vector()
{
delete buf;
}
// the `assignment operator` is forassignment statements
Vector &Vector ::operator =(Vector &v)
{
for (int i = 0; i < sz; i++)
buf[i] = v.buf[i];
return *this; // Allows v1 = v2 = v3;
}
// the `copy constructor` is forinitialization from another object
// includes parameter passing by copy andfunction return value
Vector ::Vector(const Vector &v)
{
sz = v.sz;
buf = new int[sz];
for (int i = 0; i < sz; i++)
buf[i] = v.buf[i];
}
// exception handling allows reliable handling of run-timeerrors
struct size_error{
int value;
size_error(int i): value(i) {}
};
struct range_error{
int value;
range_error(int i): value(i) {}
};
class Vector {
int *buf;
int sz;
public:
Vector(int size): sz(size) {
if (size < 1) throw size_error(size);
buf = new int[size];
}
int &operator [](int i) {
if (!in_range(i)) throw range_error(i);
return buf[i];
}
};
int do_vector_stuff(){
try {
int n = -1;
Vectorv(n);
n = 10;
Vector v(n);
v[n] = v[n/2];
}
catch (size_error &e) {
cerr << "size error for vector: size = " << e.value<< ' ';
return 0;
}
catch (range_error &e) {
cerr << "range error for vector: index = " << e.value<< ' ';
return -1;
}
I hope this will helpful foryou...........
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.