
9.17 Lab 7: Dynamic Arrays Using
Provide full code for main.cpp, dynamicarray.h and dynamic.cpp
Step 1: Preparation
For the moment, "comment out" the following under-construction code:
- dynamicarray.h: All function prototypes except the constructors and destructor. Keep the member variables for now.
- dynamicarray.cpp: All function implementations except the constructors and destructor. Remove (not just comment out) INITIAL_CAP, and replace it with a hard-coded 10 inside the default constructor.
- main.cpp: Comment out all the code inside the RunPart1Tests function between the lines. Comment out all the code starting with the "Equality comparison" comment and just before the "return 0;" line.
bool pass = true;
and
return pass;
Step 2: Replacing Member Data and the Two Constructors
Replace the current member data (arr, len, and capacity) with a single vector of integers.
- At the top of your .h, include the <vector> library. Also, remove your current member data, and replace it with a vector of ints. Name it "arr" so you can keep as much of your current code as possible.
Next, change the constructor and destructor.
- The implementation is now { }. You could remove the default constructor from the class but might as well be explicit
- For the copy constructor, copy the vector from the other object. One way to do so would be to do an element-by-element copy. The other is that we can use the copy constructor that's defined for the STL vector class through what is called a constructor initialization list. The new copy constructor:
DynamicArray::DynamicArray(const DynamicArray& other) : arr(other.arr) { }
The ": arr(other)" is the initialization list. It specifies how to construct each of the class's member variables and uses the copy constructor of the STL vector class.
- For destructor, deallocate any memory we dynamically allocated. The destructor is also now { }.
The code should report the Lab 6 tests as "passed."
Step 3: The One-Liners Plus Output
Tackle four member functions (cap(), at(), append() and operator=) that translates well to functions that the vector class provides for you. You'll also tackle print.
- Uncomment the declarations and definitions of these functions from the .h and .cpp files.
- Replace your cap() function (defined in the .h) with a single-line function that uses a member function of the vector class.
- Do the same for your at() function. Do NOT return -11111 when out-of-bounds. It's OK if your code throws an exception (which will cause a crash) for out-of-bounds errors.
- Do the same for your append() function.
- Repeat for the = operator. This will be two lines: one to actually copy the vector, and then the obligatory return * this;
Look at the output function: print(). It makes reference to two member variables: arr[i] and len. Replace these references with the appropriate ways to access them using your new vector.
Go to the RunPart1Tests function in main.cpp. Put everything back in until the line labeled "Test sum."
Two bad things are going to happen:
- You're going to fail two capacity tests. You can comment out the sections that test the capacity.
- THIS CODE SHOULD CRASH, with an error message including:
terminate called after throwing an instance of 'std::out_of_range: vector'
Step 4: The remaining functions
You should have three functions left.
sum
Steps:
- Un-comment it from dynamicarray.h
- In dynamicarray.cpp, make similar modifications to the ones you made for print()
- In main.cpp, put the "Test sum" section back into RunPart1Tests().
You should now be passing all the current tests.
operator==
The vector function doesn't have an equality operator, so your code still has to do the work of defining one.
- Uncomment it from your .h
- Modify the implementation as necessary
- In the main() function of main.cpp, put the Equality Comparison tests back in.
Recompile and rerun. Everything should pass.
remove
Last but not least; remove().
- Uncomment it from your .h
- Modify the implementation as follows
- Find valToDelete in the vector, and return false if it's not there.
- When you find it, you need to call vector's erase function and pass it an iterator for the position you want to delete.
vector.begin() + i where i is the position of the element. Then return true.
- In function RunPart1Tests() in main.cpp, put everything back except the capacity tests that's commented out, and the single (long) line of code under a.remove(100 + i). You should be passing all the Part 1 tests.
- In function main() in main.cpp, uncomment the rest of the code. All tests should pass with desired output.
Step 5: Overloading the output (<<) operator
Define and implement the output operator, which mirrors the print() method. Recall signature of this method is:
friend ostream& operator<< (ostream &out, const DynamicArray& objToPrint);
Replace the following lines at the end of main():
stringstream testoutput;
a.print(testoutput);
b.print(testoutput);
cout << testoutput.str();
with
cout << a << b;

Step by stepSolved in 4 steps with 1 images

- // Description: Write a function Partition (f, l, p, a) // which partitions array a into two parts, left and right. // Elements of a in the left part should be smaller than p, // and the elements of a great than or eqaul to p should be in the right part. // F should set to the first element of a partition of array a to be partioned, // and l is the left element of a to be subjected to the partition. In C++ please, must include partition and swap functionsarrow_forwardWrite a function mountains example on how the function works is given in the image.arrow_forward3.1 Write a function called matrix_classifier that has one input called Matrix 1 represented as a numpy array. The function should classify the matrix as one of (i) one-to-one, (ii) onto, (iii) both (i.e. invertible), or (iv) neither. It should return the classification represented as a string (i.e. either "one-to-one", "onto", "invertible", or "neither"). In Student's answer import numpy as np def matrix_classifier (Matrix1): # Check if the matrix is square if Matrix1.shape [0] != Matrix1.shape [1]: return "neither" # Not square, cannot calculate det # Calculate the determinant of the matrix det = np. linalg.det (Matrix1) # Calculate the rank of the matrix rank = np.linalg.matrix_rank (Matrix1) if det! 0: # If the determinant is nonzero, it's invertible return "invertible" elif rank (Top) Matrix1.shape [1]: # If the rank is less than the number of columns, it return "neither" else: # If the rank equals the number of columns, check if if rank Matrix1.shape [0]: return "onto" return…arrow_forward
- Presentation exercise 2 Write a function (including docstring) called multiply_term that takes a polynomial as inputs and a term. We can represent polynomials as a collection or power-coefficient pairs. Consider the following polynomial: p(x) = 2 - a4 – 3. x+ 5. We can represent it as the following collection of pairs: (4, 2), (1, -3), (0, 5). We can represent a term as a tuple where the first value indicated the exponent in the term, and the second its coefficient. For example, the term 5 - a* is represented by the tuple (4, 5). The function does not return anything, but after its execution the input dictionary will now represent the multiplication of the input polynomial by the specified term. For example: Page 2 >> p = {2 : 1, 1 : 2} # x^2 + 2x >>> t = (4, 5) # 5x^4 >>> multiply_term(p, t) >>> p == {6 : 5, 5 10} True You can assume that the function will receive as input a dictionary mapping integers to numbers. No need for you to implement any type of input validation.arrow_forwardHi, OCaml programming 1. Create a type slidingTile, consisting of a char matrix and two integers xand y. The integers x and y are the coordinates of an empty tile. 2. Create a function val slide : slidingTile -> int -> int -> slidingTile = <fun> that given a slidingTile and two integers, that represent a location in thematrix, it slides the tile from the specified location to the empty tile, thenreturns the altered slidingTile. If provided location is not adjacent to theempty tile, or out of bounds, then return the slidingTile unaltered. 3. Create a function val print_tile : slidingTile -> unit = <fun> that prints a slidingTile on screen with the corresponding characters fromthe matrix. However, print an empty space where the empty tile is instead.arrow_forwardExercise 4.2: Write a C++ program using array and loop that prompts a user to enter 15 Students' marks in Program Design and Implementation (PDI) Module in an array. The program sorts the students' marks in descending order using a loop and displays the marks of all students as well as lowest, highest, average marks, and the class result based on the average module marks. The result criteria is given below: Average is less than 40 = Poor Result Average is between 40 to 49 = Fair Result Average is less than 50 to 59= Good Result Average is less than 60 to 69 = Very Good Result Average is between 70 to 79 = Excellent Result Average is 80 or greater = Outstanding Result Note: You must demonstrate the use of arrays and loops. Your code must be properly commented. Sample Output: Welcome to Result Management System Enter PDI Marks of Student 1: 50 Enter PDI Marks of Student 2: 35 Enter PDI Marks of Student 3: 30 Enter PDI Marks of Student 4: 65 Enter PDI Marks of Student 5: 70 Enter PDI…arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education





