Question

In: Computer Science

Learning Outcomes Implement a dynamically resizable array and analyze its performance. Instructions Our last program was...

Learning Outcomes

  • Implement a dynamically resizable array and analyze its performance.

Instructions

Our last program was to maintain a list of Planets in the STL’s vector class. In this assignment, you will be writing your own vector class. Implement class vector consisting of an array of a generic type.

This class will require the following fields:

  • mData: An array of items of a generic type.
  • mCapacity: An integer representing the capacity of the vector, which is the number of items the array can contain. Hereafter known as the capacity.
  • mSize: An integer representing the size of the vector, which is the number of items actually stored in the array. Hereafter known as the size. The capacity is always greater than or equal to the size.

Your vector class must also support the following public member functions. (Please define everything in a vector.hpp file!):

  • vector(): A default constructor which should call the initialization constructor with a value of 10.
  • vector(const vector&): A copy constructor that takes a vector object and copies its contents into a dynamically allocated array with the same capacity.
  • size(): int Returns the size of the vector.
  • push_back(const T): void Adds an item in the next open position if there is room. If there is no room, the application should allocate a new array that is twice the size of the current capacity and then copies all existing elements from the existing array to the new array. Then we delete the existing array and point our array field to the new array. This method should update the assignment count each time it performs and assigment. (This behavior of resizing the array should be its own private helper method called resizeArray(int) (where the passed int is the size of the new array).
  • operator[]: T Returns the element stored at the specified index. Historically, if the index is out-of-bounds (either for being negative or greater than/equal the size of the vector), this function does nothing to warn the user that this is the bad idea. You can do that, or you can throw invalid\_argument("Index out of bounds.");. I’m okay with either. See a better description below.

How to implement operator[]

The operator[] requires that you add TWO methods to your vector class (one which is used for reading and the other for writing). You probably haven’t implemented this before, so you’ll be given the code. Here are the prototypes used in the vector class definition. The int passed to each method represents the index desired by the user.

T& operator[](int);             // Write operation.
const T& operator[](int) const; // Read operation.

The implementation of these two methods is identical: return the element in your array at the desired index. These examples assume that your data array is named mData.

template <class T>
T& vector<T>::operator[](int index) {
    return mData[index];
}

template <class T>
const T& vector<T>::operator[](int index) const {
    return mData[index];
}

Once these two methods are added to your vector class, you may now do things such as this (provided that everything else in your vector is written correctly). Don’t put this into your code. This serves as an example of what you can do.

vector<int> list;
list.push_back(10);
list.push_back(20);
list.push_back(30);
std::cout << "Last element: " << list[list.size()-1] << std::endl;

Return to the listing of planets.

Return to your Planets library. In your Planets.h file, remove the import statements to <vector> and replace those with the local version of “vector.hpp” that you made. You will have to modify some of methods in this class in order to use your vector instead of the STL vector.

*************************************************************

* Code for Planet.h, Planets.h, and main.cpp *

*************************************************************

Planet.cpp

#include <string>

using namespace std;

class Planet {
private:
string name;
string madeOf;
int alienPopulation;
public:
Planet() {}
Planet(string name, string madeOf, int alienPopulation) {
if(name.empty())
throw "Planet Name Empty";
if(madeOf.empty())
throw "Made of Empty";
if(alienPopulation < 0)
throw "Alien Population Empty";
this->name = name;
this->madeOf = madeOf;
this->alienPopulation = alienPopulation;
}
string getName() {
return name;
}
string getMadeOf() {
return madeOf;
}
int getAlienPopulation() {
return alienPopulation;
}
};

Planets.cpp

#include <vector>
#include <climits>
#include "Planet.cpp"

using namespace std;

class Planets {
private:
vector<Planet> planets;

public:
void addPlanet(Planet p) {
planets.push_back(p);
}
int getCount() {
return planets.size();
}
Planet getMostPopulatedPlanet() {
int mostPop = INT_MIN;
int mostPopPlanet = -1;
for(int i = 0; i < planets.size(); i++) {
if(planets[i].getAlienPopulation() > mostPop) {
mostPop = planets[i].getAlienPopulation();
mostPopPlanet = i;
}
}
return planets[mostPopPlanet];
}
Planet get(int i) {
if(i < 0 || i > getCount() - 1)
throw "ArrayIndexOutOfBound";
return planets[i];
}
};

main.cpp

#include <iostream>
#include "Planets.cpp"

using namespace std;

Planet newPlanet( ) {
cout << "Enter the Name, MadeOf, and Alien Population of the planet :\n";
string name, madeOf;
int population;
cin >> name >> madeOf >> population;
Planet p(name,madeOf,population);
return p;
}

int main() {
int choice;
bool run = true;
Planet temp;
Planets p;
while(run) {
cout << "*******Planets Menu*********\n";
cout << "****************************\n";
cout << "1. Add Planet\n";
cout << "2. Get Planet Count\n";
cout << "3. Get the Most Populated Planet\n";
cout << "4. Exit\n";
cout << "Enter your choice:\t";
cin >> choice;
switch(choice) {
case 1:
p.addPlanet(newPlanet());
break;
case 2:
cout << "Number of Planet(s): " << p.getCount() << endl;
break;
case 3:
temp = p.getMostPopulatedPlanet();
cout << "the most populated planet is: " << temp.getName() << " with " << temp.getAlienPopulation() << " that is made of " << temp.getMadeOf() << endl;
break;
case 4:
run = false;
break;
}
}
return 0;
}

Solutions

Expert Solution

// vector.hpp

#ifndef VECTOR_HPP_

#define VECTOR_HPP_

#include <iostream>

template <class T>

class vector

{

public:

       vector(); // default constructor

       vector(const vector&); // copy constructor

       ~vector(); // destructor

       int size(); // return size of vector

       void push_back(const T); // insert the element at the end of vector

       T& operator[](int);             // Write operation.

       const T& operator[](int) const; // Read operation.

private:

       int mCapacity;

       int mSize;

       T *mData;

};

// default constructor to create an empty vector of capacity 10

template <class T>

vector<T>::vector()

{

       mCapacity = 10;

       mSize = 0;

       mData = new T[mCapacity];

}

// copy constructor to create a vector same as other vector

template <class T>

vector<T>::vector(const vector<T> &other)

{

       mCapacity = other.mCapacity;

       mSize = other.mSize;

       mData = new T[mCapacity];

       for(int i=0;i<mSize;i++)

             mData[i] = other.mData[i];

}

// function to return the number of elements currently in the vector

template <class T>

int vector<T>::size()

{

       return mSize;

}

// function to add an element at the end of vector if there is room, else increase the size to twice its capacity and insert the element

template <class T>

void vector<T>:: push_back(const T val)

{

       if(mSize == mCapacity) // check if vector is full, then increment its size

       {

             T *temp = new T[2*mCapacity];

             mCapacity = 2*mCapacity;

             for(int i=0;i<mSize;i++)

                    temp[i] = mData[i];

             delete [] mData;

             mData = temp;

       }

       // insert the element at the end

       mData[mSize] = val;

       mSize++;

}

// function to store the element at index

template <class T>

T& vector<T>::operator[](int index) {

    if(index >=0 && index < mSize)

       return mData[index];

    else

       throw std::invalid_argument("Index out of bounds.");

}

// function to return the element at index

template <class T>

const T& vector<T>::operator[](int index) const {

    if(index >=0 && index < mSize)

       return mData[index];

    else

       throw std::invalid_argument("Index out of bounds.");

}

// destructor to release the memory allocated to mData dynamically

template <class T>

vector<T>::~vector()

{

       delete [] mData;

}

#endif /* VECTOR_HPP_ */

//end of vector.hpp

// Planet.cpp

#include <string>

using namespace std;

class Planet {

private:

       string name;

       string madeOf;

       int alienPopulation;

public:

       Planet() {}

       Planet(string name, string madeOf, int alienPopulation) {

             if(name.empty())

                    throw "Planet Name Empty";

             if(madeOf.empty())

                    throw "Made of Empty";

             if(alienPopulation < 0)

                    throw "Alien Population Empty";

             this->name = name;

             this->madeOf = madeOf;

             this->alienPopulation = alienPopulation;

       }

       string getName() {

             return name;

       }

       string getMadeOf() {

             return madeOf;

       }

       int getAlienPopulation() {

             return alienPopulation;

       }

};

//end of Planet.cpp

// Planets.cpp

//#include <vector>

#include "vector.hpp"

#include <climits>

#include "Planet.cpp"

using namespace std;

class Planets {

private:

       vector<Planet> planets;

public:

       void addPlanet(Planet p) {

             planets.push_back(p);

       }

       int getCount() {

             return planets.size();

       }

       Planet getMostPopulatedPlanet() {

             int mostPop = INT_MIN;

             int mostPopPlanet = -1;

             for(int i = 0; i < planets.size(); i++) {

                    if(planets[i].getAlienPopulation() > mostPop) {

                           mostPop = planets[i].getAlienPopulation();

                           mostPopPlanet = i;

                    }

             }

             return planets[mostPopPlanet];

       }

       Planet get(int i) {

             if(i < 0 || i > getCount() - 1)

                    throw "ArrayIndexOutOfBound";

             return planets[i];

       }

};

//end of Planets.cpp

// main.cpp

#include <iostream>

#include "Planets.cpp"

using namespace std;

Planet newPlanet( ) {

       cout << "Enter the Name, MadeOf, and Alien Population of the planet :\n";

       string name, madeOf;

       int population;

       cin >> name >> madeOf >> population;

       Planet p(name,madeOf,population);

       return p;

}

int main() {

       int choice;

       bool run = true;

       Planet temp;

       Planets p;

       while(run) {

       cout << "*******Planets Menu*********\n";

       cout << "****************************\n";

       cout << "1. Add Planet\n";

       cout << "2. Get Planet Count\n";

       cout << "3. Get the Most Populated Planet\n";

       cout << "4. Exit\n";

       cout << "Enter your choice:\t";

       cin >> choice;

       switch(choice) {

             case 1:

                    p.addPlanet(newPlanet());

                    break;

             case 2:

                    cout << "Number of Planet(s): " << p.getCount() << endl;

                    break;

             case 3:

                    temp = p.getMostPopulatedPlanet();

                    cout << "the most populated planet is: " << temp.getName() << " with " << temp.getAlienPopulation() << " that is made of " << temp.getMadeOf() << endl;

                    break;

             case 4:

                    run = false;

                    break;

             }

       }

       return 0;

}

//end of main.cpp

Output:


Related Solutions

In C++ Write a program that dynamically allocates a built-in array large enough to hold a...
In C++ Write a program that dynamically allocates a built-in array large enough to hold a user-defined number of test scores. (Ask the user how many grades will be entered and use a dynamic array to store the numbers.) Once all the scores are entered, the array should be passed to a function that calculates the average score. The program should display the scores and average. Use pointer notation rather than array notation whenever possible. (Input Validation: Do not accept...
C++ PLEASE---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In this program, you will analyze an array
C++ PLEASE---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In this program, you will analyze an array of 10 characters storing a gene sequence. You will be given a subsequence of 3 characters to look for within this array. If the subsequence is found, print the message: Subsequence <XXX> found at index <i>. Where i is the starting index of the subsequence in the array. Otherwise, print Subsequence <XXX> not found. The array of characters and the subsequence will be given through standard input. Read them and...
Learning Outcomes Using Java, maintain a collection of objects using an array. Construct a class that...
Learning Outcomes Using Java, maintain a collection of objects using an array. Construct a class that contains an array as a private instance variable. Construct methods with arrays as parameters and return values. Use partially filled arrays to implement a class where objects can be dynamically added. Implement searching and sorting algorithms. Instructions For this assignment you will be implementing an application that manages a music collection. The application will allow the user to add albums to the collection and...
in C++ For this program, you are going to implement a stack using an array and...
in C++ For this program, you are going to implement a stack using an array and dynamic memory allocation. A stack is a special type of data structure that takes in values (in our case integers) one at a time and processes them in a special order. Specifically, a stack is what's called a first-in-last-out (FILO) data structure. That is to say, the first integer inserted into the stack is the last value to be processed. The last value in...
c++ You will implement a template class with the following members: An array of our generic...
c++ You will implement a template class with the following members: An array of our generic type. The size of this array should be determined by an integer argument to the constructor. An integer for storing the array size. A constructor capable of accepting one integer argument. The constructor should initialize the array and set the array size. A method, find Max, that returns the maximum value in the array. A method, find Min, that returns the minimum value in...
Your boss, the CEO, asks you to analyze our company's performance in relation to our competitors,...
Your boss, the CEO, asks you to analyze our company's performance in relation to our competitors, but she only gives you a short timeframe for the project. You can do this either by comparing the firms' balance sheets and income statements or by comparing the firms' ratios. If you only had time to use one means of comparison, which method would you use and why? What are the drawbacks of using your selected method? It is commonly recommended that the...
Your boss, the CEO, asks you to analyze our company's performance in relation to our competitors,...
Your boss, the CEO, asks you to analyze our company's performance in relation to our competitors, but she only gives you a short timeframe for the project. You can do this either by comparing the firms' balance sheets and income statements or by comparing the firms' ratios. If you only had time to use one means of comparison, which method would you use and why? What are the drawbacks of using your selected method? It is commonly recommended that the...
Instructions Write a program to implement the algorithm that you designed in Exercise 19 of Chapter...
Instructions Write a program to implement the algorithm that you designed in Exercise 19 of Chapter 1. Your program should allow the user to buy as many items as the user desires. Instructions for Exercise 19 of Chapter 1 have been posted below for your convenience. TEXT ONLY PLEASE (PLEASE NO PDF OR WRITING) C++ CODE Exercise 19 Jason typically uses the Internet to buy various items. If the total cost of the items ordered, at one time, is $200...
Case Study: Renal Physiology Learning Outcomes: Apply physiological and biochemical knowledge to analyze case studies on...
Case Study: Renal Physiology Learning Outcomes: Apply physiological and biochemical knowledge to analyze case studies on pathological states. Communicate biological information effectively in written work. Apply physiology to relevant societal impacts. Directions: Please read the provided case study and then answer the following questions. Your answers should be complete and detailed, including all relevant physiological details including hormones and renal control mechanisms. Each answer should be at least one paragraph. A 24-year-old man visits his primary care physician after suddenly...
sing arrays please write a program to implement the STACK concept after creating the Array, the...
sing arrays please write a program to implement the STACK concept after creating the Array, the user is to be presented with a menu to choose from a number of options such as pop, push, top, etc... elements to be added on the stack are ints between 0 and 99 include a loop to re display the options (menu) and an outer loop to restart the program Write a C++ program to implement the Stacks concept. the stack implementation is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT