Question

In: Computer Science

Function Template and Exception Handling In part one, you are going to implement the selection sort...

Function Template and Exception Handling

In part one, you are going to implement the selection sort function that is capable of sorting vectors of int, double or string. In part two you will be writing a try catch block to catch the out-of-range exception.

You are to write three functions and manipulate main() function for this lab all of which should be written in one main.cpp file:

Part one:

unsigned min_index(const vector<T> &vals, unsigned index): Passes in an index of type int and a vector of type T (T could be string, double or int). The function returns the index of the min value starting from "index" to the end of the "vector".

selection_sort(vector<T> &vals): Passes in a vector of type T and sorts them based on the selection sort method. This function should utilize the min_index function to find the index of the min value in the unsorted portion of the vector.

Part two:

T getElement(vector<T> vals, int index): Passes in a vector of type T (T could be string, double or int) and an index of type int. The function returns the element located at the index of the vals. You should write up a try catch block in main function so that when the index is out of the range of the vector, the "std::outofrange" exception will be caught by the catch (const std::outofrange& excpt). Once the exception is caught, it should output "out of range exception occured" followed by a new line.

You are given a function that creates a vector of characters with random size. You just need to put the following piece of code in your main.cpp file as is:

vector<char> createVector(){
    int vecSize = rand() % 26;
    char c = 'a';
    vector<char> vals;
    for(int i = 0; i < vecSize; i++)
    {
        vals.push_back(c);
        c++;
    }
    return vals;
}

Here is the main function you can use. You should add try/catch block to this function so that if index is out of range in calling getElement function, it should output "out of range exception occured" followed by a new line. You should include <stdexcept> library in your program which contains definitions for a set of standard exceptions.

int main(){

    //Part B
     srand(time(0));
     vector<char> vals = createVector();
     char curChar;
     int index;
     int numOfRuns = 10;
     while(--numOfRuns >= 0){
         cout << "Enter a number: " << endl;
         cin >> index;
         curChar = getElement(vals,index);
         cout << "Element located at " << index << ": is " << curChar << endl;
    }
    return 0;
}

You should come up with test harnesses to test your selection_sort function.

In this lab, you are going to write a template function that is capable of sorting vectors of characters, intgeres and strings.

Submission Instructions

Compile command

g++ main.cpp -Wall -Werror -o a.out

We will use this command to compile your code

Solutions

Expert Solution

Here is the solution to above problem in C++. Please read the code comments for more information

GIVE A THUMBS UP!!!

C++ Code

#include<iostream>
#include<vector>
#include<string>
#include<stdlib.h>
#include<time.h>
using namespace std;
template<typename T>
//find the minimum index in range from index
unsigned min_index(const vector<T> &vals, unsigned index)
{
   int min_idx=index;
   //for loop to find minimum
   for (int j = index+1; j < vals.size(); j++)
if (vals[j] < vals[min_idx])
min_idx = j;
return min_idx;
}

template<typename T>
T getElement(vector<T> vals, int index)
{
   //get element at index location
   for(int i=0;i<vals.size();++i)
   {
       if(i==index)
           return vals;
   }
}

template<typename T>
void selection_sort(vector<T> &vals)
{
   int min_idx;
   //check the size
for (int i = 0; i < vals.size()-1; i++)
{   
//find the minimum index
       min_idx = min_index(vals,i);
       //swap the values found
T temp = vals[min_idx];
vals[min_idx]=vals[i];
vals[i]=temp;
}
}


//here is the Create a vector
vector<char> createVector(){
int vecSize = rand() % 26;
char c = 'a';
vector<char> vals;
for(int i = 0; i < vecSize; i++)
{
vals.push_back(c);
c++;
}
return vals;
}

int main()
{
   vector<char> vals = createVector();
   selection_sort(vals);
   cout<<"Sorted vector\n";
   for(int i=0;i<vals.size();++i)
   {
       cout<<vals[i]<<" ";
   }
   return 0;
}

Screenshot of output


Related Solutions

A template (generic) function for insertion sort is given to you. Part-1: design a function to...
A template (generic) function for insertion sort is given to you. Part-1: design a function to compare 2 strings using case-insensitive comparison, a function to test if 2 records are not equal (using case-insensitive string comparison). Part-2: define your own compare function required by the template insertionSort function. #include <iostream> #include <string> #include <cstdlib> #include <iomanip> #include <ctime> #define BASE 1000000000LL // long long int using namespace std; struct record { long long value; string str; }; // Part-1: case-insensitive...
C++.how to write a selection sort to sort it. read_book_data() This member function takes one parameter,...
C++.how to write a selection sort to sort it. read_book_data() This member function takes one parameter, a string that contains the name of a file. This string parameter can be a C++ string or a C string (your choice). The function returns nothing. This constructor should do the following: Declare and open an input file stream variable using the file name string passed in as a parameter. Check to make sure the file was opened successfully. If not, print an...
4) Implement the Selection Sort algorithm discussed in class to sort a list of a certain...
4) Implement the Selection Sort algorithm discussed in class to sort a list of a certain size. The list is to be implemented using a dynamic array as well as a singly linked list. You are required to compare the performance (sorting time) for the dynamic array and singly-linked list-based implementations. You are given the startup codes for the dynamic array and singly-linked list based implementations. You are required to implement the Selection Sort function in each of these codes....
All code in JAVA please 1. Implement Insertion Sort 2. Implement Selection Sort *For problem 1...
All code in JAVA please 1. Implement Insertion Sort 2. Implement Selection Sort *For problem 1 and 2, please: a. Let the program generate a random array. b. Output both the original random array and the sorted version of it
In this project you will implement and experiment with three different sorting algorithms: Insertion Sort, Selection...
In this project you will implement and experiment with three different sorting algorithms: Insertion Sort, Selection sort and Bubble Sort. The objective of this project is to understand the relation between the theoretical asymptotic complexities (Big-O) computed in class and the actual running times for different kinds of input. The enclosed source file main.cpp contains a program that reads two inputs: a letter specifying which sorting algorithm to use (I for InsertionSort , S for SelectionSort and B for BubbleSort),...
Bubble and Selection Sort For this assignment, you are to consider bubble and selection sort. Both...
Bubble and Selection Sort For this assignment, you are to consider bubble and selection sort. Both are O(n^2) however it may be possible to classify one algorithm as being more efficient than the other. You are to discuss which algorithm you feel is the most efficient and in what cases it will be more efficient. Provide any relevant test cases and code to support your belief. Submit a pdf containing your findings and test results along with any relevant code...
C++ Part 1: Developing And Testing A Stack Template Write a template, Stack.h, to implement a...
C++ Part 1: Developing And Testing A Stack Template Write a template, Stack.h, to implement a LIFO stack. Here is the specification for its public interface: class Stack { ... Stack( ); // may have a defaulted parameter Stack(const Stack<V>&); // copy constructor ~Stack(); Stack<V>& operator=(const Stack<V>&); void push(const V&); const V& peek( ); void pop( ); int size( ) const; bool empty( ) const; void clear( ); }; If you use dynamic memory (and you surely will!) be sure...
Design two function templates as follows: - First function template will be used to sort arrays...
Design two function templates as follows: - First function template will be used to sort arrays of different data types in either descending or ascending order. This function template is required to have the following parameters: an array of a generic type, an integer representing the size of the array, and a character representing the order of sorting (i.e., ascending or descending). The last argument (i.e., the order of sorting) is required to be a default argument. The default order...
USING MATLAB Part 2: Insert coins For this part, you are going implement the code that...
USING MATLAB Part 2: Insert coins For this part, you are going implement the code that asks the user to enter coins until they have entered enough for the NAU power juice. Open the insert_coins.m file. Initialize total to 0. We do this because initially, no coins have been entered. Using a loop, ask the user to enter a coin until the total matches or exceeds 115 cents. The input should be a char or string, so make sure that...
Selection Sort Programmatically Implement in C++ the necessary program that does the following: Asks the user...
Selection Sort Programmatically Implement in C++ the necessary program that does the following: Asks the user and gets at least 5 whole numbers as user input from the keyboard and stores them in an array Displays the numbers from the array on the screen Sorts the numbers in the array using SELECTION SORT Algorithm Displays the sorted numbers on the screen from the array Save your code file as "yourLastname_Firstname_SelectionSort.cpp" and submit your .cpp file. NOTE: This assignment needs only...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT