Isaac H.

asked • 04/05/23

Define a copy method void copy(const vector* other) and add it/incorporate it into the vector class definition.

Review the entire code. Define a copy method void copy(const vector* other) and add it/incorporate it into the vector class definition (i.e. the file you will submit should have everything our vector class has + new method copy). The copy method is given a pointer to the other vector object and should copy all the information from that vector to this vector. Note that you cannot guarantee that this and the other vector are the exact same sizes.

#include <iostream>
class vector {
int sz; // the size
double * elem; // a pointer to the elements

public:
vector(int s): sz(s), elem(new double[s]) { // constructor
for (int i{0}; i < s; ++i) elem[i] = 0;
}

~vector() { // destructor
delete[] elem;
}
double get(int n) const {return elem[n];}; // access:read
void set(int n, double v) {elem[n] = v;} // access:write
int size() const {return sz;} // the current size
// a member function that would display the values of the vector object
void display() {
for (int i{ 0 }; i < sz; ++i)
std::cout << elem[i] << " ";
}
/* a member function resize(int newSz) that resizes the vector to the new size,
preserving all the existing elements */
void resize(int newSz) {
double* tmp = new double[newSz]; // allocate new space
for (int i{0}; i < sz; ++i) // copy the existing values
tmp[i] = elem[i];
for (int i{sz}; i < newSz; ++i) // the rest of the places are filled with 0s
tmp[i] = 0;
delete[] elem; // release the space pointed to by elem
elem = tmp; // reassign the elem pointer to the newly allocated array
sz = newSz; // update the size
}

};
// not "frending" it with vector class this time
// overloading the output operator<< to be used with objects of this class
std::ostream & operator<<(std::ostream & out, const vector & v) {
for (int i{0}; i < v.size(); ++i)
out << v.get(i) << " ";
return out;
}
int main() {
vector a(10); // create a vector of 10 elements
// filling it with values 1, 3, 5, ..., 19
for(int i{0}; i<10; ++i)
a.set(i, 2 * i + 1);
// using overloaded output stream operator
std::cout << a << std::endl;
//changing the size to 20 elements
a.resize(20);
std::cout << "\nThe element of the vector after resizing: \n" << a << std::endl;
}

1 Expert Answer

By:

Jerry C. answered • 04/06/23

Tutor
New to Wyzant

Gain Confidence with Math

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.