Please provide the c++ code as well as a screenshot of the working program! Than
ID: 3789922 • Letter: P
Question
Please provide the c++ code as well as a screenshot of the working program!Thanks Header File override C++ vector definition #ifndef VECTOR H #define VECTOR H class Vector public: Vector 0; ll default constructor Vector (int s); ll makes size //allocates s space ll e.g. entries new int[size] ll makes all entries 0 Vector (const Vector & other); Il copy constructor ll makes a deep copy Vector 0 ll default destructor Il Prints out the vector void print 0; void set int val, int pos); Il if 0 pos
Explanation / Answer
/*
* File: Vector.h
*/
#ifndef VECTOR_H
#define VECTOR_H
class Vector{
private:
int size; //set the no of elements used
int *entries; //point to array of int with size entries, eg- entries=new int[size]
public:
Vector(); //default constructor
Vector(int s); //make size=s, allocate s space, e.g- entries=new int[size],make all entries 0
Vector(const Vector &other);//copy constructor, makes a deep copy
~Vector(); //default destructor
void print(); //prints out the vector
void set(int val,int pos);//if0<=pos<size, store val at pos in entries, otherwise show error mmessage
};
#endif /* VECTOR_H */
//Vectors.cpp- implementation file
#include<iostream>
#include"Vector.h"
using namespace std;
Vector::Vector(){ //default constructor
size=0;
entries=NULL;
}
Vector::Vector(int s){
size=s;
entries=new int[size];
for(int i=0;i<s;i++)
entries[i]=0;
}
Vector::Vector(const Vector& other){//copy constructor
size=other.size;
entries=other.entries;
}
Vector::~Vector(){
delete []entries;
size=0;
}
void Vector::set(int val, int pos){
if(pos<0||pos>=size)
cout<<"Invalid input for position; it must be between 0 and "<<size<<endl;
else
entries[pos]=val;
}
void Vector::print(){
cout<<"[";
for(int i=0;i<size;i++)//if the entry to be displayed is not the last entry put a space after it
if(i==size-1)
cout<<entries[i];
else
cout<<entries[i]<<" ";
cout<<"] ";
}
//main file
#include <cstdlib>
#include<iostream>
#include"Vector.h"
using namespace std;
int main() {
Vector a,b(3),c(3);
cout<<"Vector a:- ";
a.print();
cout<<"Vector b:- ";
b.print();
cout<<"O/P for c.set(0,-1):-"<<endl;
c.set(0,-1);
c.set(1,0);
c.set(2,1);
c.set(3,2);
cout<<"O/P for c.set(4,3):-"<<endl;
c.set(4,3);
cout<<"c= ";
c.print();
Vector d(c);
cout<<"d= ";
d.print();
d.set(0,1);
cout<<"new value of d= ";
d.print();
return 0;
}
O/P is shown below:-
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.