Question

Can someone please help? Thanks in advance!

Simple Vector Modification C++ Your program Assignment Modify the Simple Vector class template presented in this Chapter 16-11) to include the member functions push_back and pop_back. First the User will enter the numbers that are to be in the array. The push_back function should accept an argument and insert its value at the end of the array that has been created. The pop_back function should accept no argument and remove the last element from the array. Use this created program to text the class.

Example Enter number of elements to put in a vector (between 2 and 20): 8 A vector of integers will be created first Vector c

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>

using namespace std;

template < class T >
  class SimpleVector {
    private:
      T * aptr; // To point to the allocated array
    int arraySize; // Number of elements in the array
    void memError(); // Handles memory allocation errors
    void subError(); // Handles subscripts out of range

    public:
      SimpleVector() {
        aptr = 0;
        arraySize = 0;
      }
    SimpleVector(int);
    SimpleVector(const SimpleVector & );
    ~SimpleVector();
    int size() const {
      return arraySize;
    }
    T getElementAt(int position); // return a specific element
    T & operator[](const int & );
    void pushBack(const T & newItem);
    void popBack();
  };

template < class T >
  SimpleVector < T > ::SimpleVector(int s) {
    arraySize = s;
    // Allocate memory for the array.
    try {
      aptr = new T[s];
    } catch (bad_alloc) {
      memError();
    }

    // Initialize the array.
    for (int count = 0; count < arraySize; count++)
      *
      (aptr + count) = 0;
  }

template < class T >
  SimpleVector < T > ::SimpleVector(const SimpleVector & obj) {
    // Copy the array size.
    arraySize = obj.arraySize;
    // Allocate memory for the array.
    aptr = new T[arraySize];
    if (aptr == 0)
      memError();

    // Copy the elements of obj's array.
    for (int count = 0; count < arraySize; count++)
      *
      (aptr + count) = * (obj.aptr + count);
  }

template < class T >
  SimpleVector < T > ::~SimpleVector() {
    if (arraySize > 0)
      delete[] aptr;
  }

template < class T >
  void SimpleVector < T > ::memError() {
    cout << "ERROR:Cannot allocate memory.\n";
    exit(EXIT_FAILURE);
  }

template < class T >
  void SimpleVector < T > ::subError() {
    cout << "ERROR: Subscript out of range.\n";
    exit(EXIT_FAILURE);
  }

template < class T >
  T SimpleVector < T > ::getElementAt(int sub) {
    if (sub < 0 || sub >= arraySize)
      subError();
    return aptr[sub];
  }

// Overloaded [] operator. The argument is a subscript. *
// This function returns a reference to the element *
// in the array indexed by the subscript. *

template < class T >
  T & SimpleVector < T > ::operator[](const int & sub) {
    if (sub < 0 || sub >= arraySize)
      subError();
    return aptr[sub];
  }

//Appends a new element increasing vector's size by 1
template < class T >
  void SimpleVector < T > ::pushBack(const T & newItem) {
    //allocate a new array of current size + 1
    int newSize = arraySize + 1;
    T * newArr = new T[newSize];

    //copy existing elements
    for (int count = 0; count < arraySize; count++)
      *
      (newArr + count) = * (aptr + count);
    //add the new element
    *(newArr + newSize - 1) = newItem;

    //destroy old array
    delete[] aptr;

    //store new info in instance fields
    aptr = newArr;
    arraySize = newSize;
  }

// Removes vector's last element & reducing vector's size by 1
template < class T >
  void SimpleVector < T > ::popBack() {
    //allocate a new array of current size - 1
    int newSize = arraySize - 1;
    T * newArr = new T[newSize];

    //copy existing elements
    for (int count = 0; count < arraySize - 1; count++)
      *
      (newArr + count) = * (aptr + count);

    //destroy old array
    delete[] aptr;

    //store new info in instance fields
    aptr = newArr;
    arraySize = newSize;
  }

int main() {
  SimpleVector < int > intTable;
  SimpleVector < double > doubleTable;

  // push_back
  cout << "\nUsing push_back() to populate.\n" << endl;
  for (double num = 1.1; num < 5; num += 1.1) {
    intTable.pushBack((int) num);
    doubleTable.pushBack(num);
  }
  // Display
  cout << "intTable contains:\n";
  for (int count = 0; count < intTable.size(); count++)
    cout << intTable[count] << " ";
  cout << endl;

  cout << "doubleTable contains:\n";
  for (int count = 0; count < doubleTable.size(); count++)
    cout << doubleTable[count] << " ";
  cout << endl;

  // pop_back
  cout << "\nUsing pop_back() to remove the last item.\n" << endl;
  intTable.popBack();
  doubleTable.popBack();

  // Display
  cout << "intTable contains:\n";
  for (int count = 0; count < intTable.size(); count++)
    cout << intTable[count] << " ";
  cout << endl;

  cout << "doubleTable contains:\n";
  for (int count = 0; count < doubleTable.size(); count++)
    cout << doubleTable[count] << " ";
  cout << endl;

  //hold screen
  cout << endl << "Press Enter to quit." << endl;
  cin.get();

  return 0;
}
Add a comment
Know the answer?
Add Answer to:
Can someone please help? Thanks in advance! Simple Vector Modification C++ Your program Assignment Modify the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hi, I have C++ programming problem here: Problem: Please modify your string type vector in for...

    Hi, I have C++ programming problem here: Problem: Please modify your string type vector in for push_back() function as below: void push_back(string str) { // increase vector size by one // initialize the new element with str } In addition, the standard library vector doesn't provide push_front(). Implement push_front() for your vector. Test your code with the main function below. int main() {    vector v1(3);    cout<<"v1: ";    v1.print(); // this should display -, -, -    for...

  • Example program #include <string> #include <iostream> #include <cmath> #include <vector> using namespace std; vector<int> factor(int n)...

    Example program #include <string> #include <iostream> #include <cmath> #include <vector> using namespace std; vector<int> factor(int n) {     vector <int> v1;     // Print the number of 2s that divide n     while (n%2 == 0)     {         printf("%d ", 2);         n = n/2;         v1.push_back(2);     }     // n must be odd at this point. So we can skip     // one element (Note i = i +2)     for (int i = 3; i <=...

  • Modify your program from Assignment # 7 part b (see below for code) by creating an...

    Modify your program from Assignment # 7 part b (see below for code) by creating an interactive GUI application that displays the list of the orders read in from the file (create a data file using your CreateBankFile.java program which has a least 10 bank account records in it and include it with your submission) and the total number of bank accounts. When your program starts it will first read the records from the Bank Account file (AccountRecords.txt) and creates...

  • Write a complete C++ program that will: Declare a vector of integers Use a pointer to...

    Write a complete C++ program that will: Declare a vector of integers Use a pointer to dynamically allocate an array of 10 elements Ask the user how many values they would like to have in the data structures Read in the user’s response and make sure that it is greater than 20 (error loop) Generate the number of integers that the user asked for and store them into both data structures. The integer values should be unique unordered values (no...

  • For this c++ assignment, Overview write a program that will process two sets of numeric information....

    For this c++ assignment, Overview write a program that will process two sets of numeric information. The information will be needed for later processing, so it will be stored in two arrays that will be displayed, sorted, and displayed (again). One set of numeric information will be read from a file while the other will be randomly generated. The arrays that will be used in the assignment should be declared to hold a maximum of 50 double or float elements....

  • C++ please Possible algorithms – (1) use and modify the algorithm from program 2 if possible;...

    C++ please Possible algorithms – (1) use and modify the algorithm from program 2 if possible; (2) use unique value array; (3) use flag array (flags used to avoid counting a number more than 1 time); (4) compute frequency distribution (use unique and count arrays); (5) use count array to store the frequency of a number. No global variable are permitted in this assignment. Do not change the code provided only write the missing code. Write the missing C++ statements...

  • C program prelab: This lab is pretty simple to describe: expand your suite of linked-list functions...

    C program prelab: This lab is pretty simple to describe: expand your suite of linked-list functions to include an ability to insert a given key into a list at a particular location; or in its correct sorted-order position; or to remove a specified key from a list or the key at a specified location. We’ve gone through the logic – though by now you should be able to work it out on your own – and we've discussed the kinds...

  • C++ Assignment - Only Implementation file( VectorDouble.cpp file) required. The header file is already given. Please help, thumbs up guaranteed. Chapter 8 discussed vectors, which are like arrays that...

    C++ Assignment - Only Implementation file( VectorDouble.cpp file) required. The header file is already given. Please help, thumbs up guaranteed. Chapter 8 discussed vectors, which are like arrays that can grow in size. Suppose that vectors were not defined in C++. Define a class called VectorDoublethat is like a class for a vector with base type double. Your class VectorDoublewill have a private member variable for a dynamic array of doubles. It will also have two member variables of type...

  • Programming Assignment 6 Write a Java program that will implement a simple appointment book. The ...

    Programming Assignment 6 Write a Java program that will implement a simple appointment book. The program should have three classes: a Date class, an AppointmentBook class, and a Driver class. • You will use the Date class that is provided on Blackboard (provided in New Date Class example). • The AppointmentBook class should have the following: o A field for descriptions for the appointments (i.e. Doctor, Hair, etc.). This field should be an array of String objects. o A field...

  • Can someone please help, third time I'm asking. I need a basic javascript with no push...

    Can someone please help, third time I'm asking. I need a basic javascript with no push or splice command. Please don't post a picture of the code,because my vision is poor and I won't be able to see it. Also, I need breakdown of what's in HTMLand what' s in javascript. All requirements are below. Thanks for your help. This is a 2 part assignment, but both parts can be completed in one program. Also, please follow ALL Required Programming...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT