Question

In: Computer Science

Can someone make this code work without using template? C++ using namespace std; template < typename...

Can someone make this code work without using template?

C++

using namespace std;

template < typename T>

   void print_array(T arr[], int size)
   {

       ofstream outfile;

       outfile.open("/Users/android/Desktop/outfile.txt");

       cout << "Printing Array: " << endl;

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

           cout << arr[i] << endl;

           outfile << arr[i] << endl;
       }
   }

template < typename T>

   class MergeHelper
   {

       int size;

       public:

           MergeHelper(int size)
           {

               this->size = size;
           }

       void merge(T Arr[], int start, int mid, int end)
       {

           // create a temp array

           T temp[end - start + 1];

           // crawlers for both intervals and for temp

           int i = start, j = mid + 1, k = 0;

           // traverse both arrays and in each iteration add smaller of both elements in temp

           while (i <= mid && j <= end)
           {

               if ((Arr[i] < Arr[j]) || (Arr[i] == Arr[j]))
               {

                   temp[k] = Arr[i];

                   k += 1;
                   i += 1;
               }
               else
               {

                   temp[k] = Arr[j];

                   k += 1;
                   j += 1;
               }
           }

           // add elements left in the first interval

           while (i <= mid)
           {

               temp[k] = Arr[i];

               k += 1;
               i += 1;
           }

           // add elements left in the second interval

           while (j <= end)
           {

               temp[k] = Arr[j];

               k += 1;
               j += 1;
           }

           // copy temp to original interval

           for (i = start; i <= end; i += 1)
           {

               Arr[i] = temp[i - start];
           }
       }

       void mergeSort(T Arr[], int start, int end)
       {

           if (start < end)
           {

               int mid = (start + end) / 2;

               mergeSort(Arr, start, mid);

               mergeSort(Arr, mid + 1, end);

               merge(Arr, start, mid, end);
           }
       }
   };

// MAIN METHOD

int main()
{

   int num_elements = 0;

   cout << "Enter a sorting size for the array (between 1 and 16): ";

   while (!(cin >> num_elements) || num_elements > SORT_MAX_SIZE || num_elements < 1)
   {

       // Explain error

       cout << "Error: Enter a number between 1 and 16: ";

       // clear previous input

       cin.clear();

       // discard previous input

       cin.ignore(123, '\n');
   }

   // what type of data do you want to enter?

   cout << "What type of data do you want to enter? " << endl;

   cout << "1: Integer" << endl;

   cout << "2: String" << endl;

   cout << "3: Dollar" << endl;

   int choice;

   cin >> choice;

   int arr_int[num_elements];

   string arr_str[num_elements];

   Dollar arr_dollar[num_elements];

   // Array<string, SORT_MAX_SIZE> stringarray;

   // Array<Dollar, SORT_MAX_SIZE> dollararray;

   // Array<int, SORT_MAX_SIZE> intarray;

   switch (choice)
   {

       case 1:
           {

               for (int i = 0; i < num_elements; i++)
               {

                   cout << "Enter element #" << i + 1 << ": ";

                   cin >> arr_int[i];
               }

               MergeHelper<int> merger(num_elements);

               merger.mergeSort(arr_int, 0, num_elements - 1);

               print_array(arr_int, num_elements);

               break;
           }

       case 2:
           {

               for (int i = 0; i < num_elements; i++)
               {

                   cout << "Enter element #" << i + 1 << ": ";

                   cin >> arr_str[i];
               }

               MergeHelper<string> merger(num_elements);

               merger.mergeSort(arr_str, 0, num_elements - 1);

               print_array(arr_str, num_elements);

               break;
           }

       case 3:
           {

               for (int i = 0; i < num_elements; i++)
               {

                   cout << "Enter element #" << i + 1 << ": ";

                   cout << "Dollars: ";

                   int whole;
                   cin >> whole;

                   double part;
                   cin >> part;

                   Dollar *buffer = new Dollar(whole, part, "Dollar");

                   arr_dollar[i] = *buffer;
               }

               MergeHelper<Dollar> merger(num_elements);

               merger.mergeSort(arr_dollar, 0, num_elements - 1);

               print_array(arr_dollar, num_elements);

               break;
           }
   }

   return 0;

}

Solutions

Expert Solution

A template is a powerful tool that is used for generating generic code for any type of data type. Let's say we have a sort STL implemented in the library but while passing an array through it we don't specify its data type that it is float or an int or a string array. Then how the code decides to take which algorithm. So here comes the templates in C++ which are used for overcoming this problem. In your code, they have utilized the same code for each of the three cases of int, string, and dollar. So if you want to do the same without using the templates then we will have to write the function MergeHelper and print_array for each of the datatype separately.

#include <bits/stdc++.h>

using namespace std;

//for intergers
void print_array(int arr[], int size)
{
    ofstream outfile;
    outfile.open("/Users/android/Desktop/outfile.txt");
    cout << "Printing Array: " << endl;
    for (int i = 0; i < size; i++)
    {
        cout << arr[i] << endl;
        outfile << arr[i] << endl;
    }
}

void print_array(string arr[], int size)
{
    ofstream outfile;
    outfile.open("/Users/android/Desktop/outfile.txt");
    cout << "Printing Array: " << endl;
    for (int i = 0; i < size; i++)
    {
        cout << arr[i] << endl;
        outfile << arr[i] << endl;
    }
}
void print_array(Dollar arr[], int size)
{
    ofstream outfile;
    outfile.open("/Users/android/Desktop/outfile.txt");
    cout << "Printing Array: " << endl;
    for (int i = 0; i < size; i++)
    {
        cout << arr[i] << endl;
        outfile << arr[i] << endl;
    }
}

//mergeHelper function for each cases

//int case
class MergeHelper
{
    int size;

public:
    MergeHelper(int size)
    {
        this->size = size;
    }
    void merge(int Arr[], int start, int mid, int end)
    {

        // create a temp array
        int temp[end - start + 1];

        // crawlers for both intervals and for temp

        int i = start, j = mid + 1, k = 0;

        // traverse both arrays and in each iteration add smaller of both elements in temp

        while (i <= mid && j <= end)
        {

            if ((Arr[i] < Arr[j]) || (Arr[i] == Arr[j]))
            {

                temp[k] = Arr[i];

                k += 1;
                i += 1;
            }
            else
            {

                temp[k] = Arr[j];

                k += 1;
                j += 1;
            }
        }

        // add elements left in the first interval

        while (i <= mid)
        {
            temp[k] = Arr[i];
            k += 1;
            i += 1;
        }

        // add elements left in the second interval

        while (j <= end)
        {
            temp[k] = Arr[j];
            k += 1;
            j += 1;
        }

        // copy temp to original interval

        for (i = start; i <= end; i += 1)
        {
            Arr[i] = temp[i - start];
        }
    }

    void mergeSort(int Arr[], int start, int end)
    {

        if (start < end)
        {

            int mid = (start + end) / 2;

            mergeSort(Arr, start, mid);

            mergeSort(Arr, mid + 1, end);

            merge(Arr, start, mid, end);
        }
    }
};

//string case
class MergeHelper
{
    int size;

public:
    MergeHelper(int size)
    {
        this->size = size;
    }
    void merge(string Arr[], int start, int mid, int end)
    {

        // create a temp array
        string temp[end - start + 1];

        // crawlers for both intervals and for temp

        int i = start, j = mid + 1, k = 0;

        // traverse both arrays and in each iteration add smaller of both elements in temp

        while (i <= mid && j <= end)
        {

            if ((Arr[i] < Arr[j]) || (Arr[i] == Arr[j]))
            {

                temp[k] = Arr[i];

                k += 1;
                i += 1;
            }
            else
            {

                temp[k] = Arr[j];

                k += 1;
                j += 1;
            }
        }

        // add elements left in the first interval

        while (i <= mid)
        {

            temp[k] = Arr[i];

            k += 1;
            i += 1;
        }

        // add elements left in the second interval

        while (j <= end)
        {

            temp[k] = Arr[j];

            k += 1;
            j += 1;
        }

        // copy temp to original interval

        for (i = start; i <= end; i += 1)
        {

            Arr[i] = temp[i - start];
        }
    }

    void mergeSort(string Arr[], int start, int end)
    {

        if (start < end)
        {

            int mid = (start + end) / 2;

            mergeSort(Arr, start, mid);

            mergeSort(Arr, mid + 1, end);

            merge(Arr, start, mid, end);
        }
    }
};

//dollar case
class MergeHelper
{
    int size;

public:
    MergeHelper(int size)
    {
        this->size = size;
    }
    void merge(Doller Arr[], int start, int mid, int end)
    {

        // create a temp array
        Doller temp[end - start + 1];

        // crawlers for both intervals and for temp

        int i = start, j = mid + 1, k = 0;

        // traverse both arrays and in each iteration add smaller of both elements in temp

        while (i <= mid && j <= end)
        {

            if ((Arr[i] < Arr[j]) || (Arr[i] == Arr[j]))
            {

                temp[k] = Arr[i];

                k += 1;
                i += 1;
            }
            else
            {

                temp[k] = Arr[j];

                k += 1;
                j += 1;
            }
        }

        // add elements left in the first interval

        while (i <= mid)
        {

            temp[k] = Arr[i];

            k += 1;
            i += 1;
        }

        // add elements left in the second interval

        while (j <= end)
        {

            temp[k] = Arr[j];

            k += 1;
            j += 1;
        }

        // copy temp to original interval

        for (i = start; i <= end; i += 1)
        {

            Arr[i] = temp[i - start];
        }
    }

    void mergeSort(Doller Arr[], int start, int end)
    {

        if (start < end)
        {

            int mid = (start + end) / 2;

            mergeSort(Arr, start, mid);

            mergeSort(Arr, mid + 1, end);

            merge(Arr, start, mid, end);
        }
    }
};

// MAIN METHOD

int main()
{

    int num_elements = 0;

    cout << "Enter a sorting size for the array (between 1 and 16): ";

    while (!(cin >> num_elements) || num_elements > SORT_MAX_SIZE || num_elements < 1)
    {
        // Explain error
        cout << "Error: Enter a number between 1 and 16: ";
        // clear previous input
        cin.clear();
        // discard previous input
        cin.ignore(123, '\n');
    }

    // what type of data do you want to enter?

    cout << "What type of data do you want to enter? " << endl;

    cout << "1: Integer" << endl;

    cout << "2: String" << endl;

    cout << "3: Dollar" << endl;

    int choice;

    cin >> choice;

    int arr_int[num_elements];

    string arr_str[num_elements];

    Dollar arr_dollar[num_elements];

    // Array<string, SORT_MAX_SIZE> stringarray;

    // Array<Dollar, SORT_MAX_SIZE> dollararray;

    // Array<int, SORT_MAX_SIZE> intarray;

    switch (choice)
    {

    case 1:
    {

        for (int i = 0; i < num_elements; i++)
        {

            cout << "Enter element #" << i + 1 << ": ";

            cin >> arr_int[i];
        }

        MergeHelper<int> merger(num_elements);

        merger.mergeSort(arr_int, 0, num_elements - 1);

        print_array(arr_int, num_elements);

        break;
    }

    case 2:
    {

        for (int i = 0; i < num_elements; i++)
        {

            cout << "Enter element #" << i + 1 << ": ";

            cin >> arr_str[i];
        }

        MergeHelper<string> merger(num_elements);

        merger.mergeSort(arr_str, 0, num_elements - 1);

        print_array(arr_str, num_elements);

        break;
    }

    case 3:
    {

        for (int i = 0; i < num_elements; i++)
        {

            cout << "Enter element #" << i + 1 << ": ";

            cout << "Dollars: ";

            int whole;
            cin >> whole;

            double part;
            cin >> part;

            Dollar *buffer = new Dollar(whole, part, "Dollar");

            arr_dollar[i] = *buffer;
        }

        MergeHelper<Dollar> merger(num_elements);

        merger.mergeSort(arr_dollar, 0, num_elements - 1);

        print_array(arr_dollar, num_elements);

        break;
    }
    }
    return 0;
}

I have just written the same code for each of the case but just changed the variable to int, string or dollars. I have utilized the polymorphism as I have used the same name for the function but based on the data type of argument the function is going to decide which one to be applied to get the answer.


Related Solutions

Can someone covert the code into C language #include<iostream> #include<iomanip> #include<ios> using namespace std; /******************************************************************************** Function...
Can someone covert the code into C language #include<iostream> #include<iomanip> #include<ios> using namespace std; /******************************************************************************** Function name: main Purpose:                   main function In parameters: b,r,i Out paramters: trun,error,total,value Version:                   1.0 Author: ********************************************************************************/ void main() {    int i;//declaring this variable to get value for quitting or calaculating series    do {//do while loop to calaculate series until user quits        cout << "Enter 1 to evaluate the series." << endl;       ...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating the average sightings from the Total Sightings array float calcAverage(float totalSightings[],int n) {    int i;    float sum=0.0;    for(i=0;i<n;i++)    sum=sum+totalSightings[i];    return sum/n; } int main() {    // n is no. of bird watchers    //flag , flag2 and flag3 are for validating using while loops    int n,i,flag,flag2,flag3;       //ch also helps in validating    char ch;   ...
I want Algorithim of this c++ code #include<iostream> using namespace std; int main() { char repeat...
I want Algorithim of this c++ code #include<iostream> using namespace std; int main() { char repeat = 'y'; for (;repeat == 'y';){ char emplyeename[35]; float basic_Salary,EPF, Dearness_Allow, tax, Net_Salary , emplyee_id; cout << "Enter Basic Salary : "; cin >> basic_Salary; Dearness_Allow = 0.40 * basic_Salary; switch (01) {case 1: if (basic_Salary <= 2,20,00) EPF = 0; case 2: if (basic_Salary > 28000 && basic_Salary <= 60000) EPF = 0.08*basic_Salary; case 3: if (basic_Salary > 60000 && basic_Salary <= 200000)...
In C++, assuming you have the following incomplete code: #include<iostream> #include <unistd.h> using namespace std; //...
In C++, assuming you have the following incomplete code: #include<iostream> #include <unistd.h> using namespace std; // Structure for storing the process data struct procData { char pname[5]; // Name of a process int arrivt; //Arrival time of a process int pburst; // Burst time of a process int endtime; // Exit time/ Leaving time of a process int remburst; // Remaining burst time of a process int readyFlag; // boolean, Flag for maintaining the process status }; // Global variable...
Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std;...
Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std; void leapYear(int x); int main() { int x; cout << "Enter a year: "; cin >> x; leapYear (x);   return 0; } void leapYear(int x ) {    if (x % 400 == 0)    {    cout << "This is a leap Year";}    else if    ((x % 4 == 0) && (x % 100 != 0))    {    cout <<...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell {...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell { int val; Cell *next; }; int main() { int MAX = 10; Cell *c = NULL; Cell *HEAD = NULL; srand (time(NULL)); for (int i=0; i<MAX; i++) { // Use dynamic memory allocation to create a new Cell then initialize the // cell value (val) to rand(). Set the next pointer to the HEAD and // then update HEAD. } print_cells(HEAD); }
C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to...
C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to store user input bool cont = true; //implement a loop so that it will continue asking until the user provides a positive integer // the following provides ONLY part of the loop body, which you should complete { cout <<"How many words are in your message? \n"; cout <<"Enter value: "; // get user input integer here    cout <<"\nInvalid value. Please Re-enter a...
C++ I took 7/20 =( code: #include <iostream> #include<string.h> using namespace std; // function to calculate...
C++ I took 7/20 =( code: #include <iostream> #include<string.h> using namespace std; // function to calculate number non white space characters int GetNumOfNonWSCharacters(string str) { int i = 0; int count = 0; while(str[i] != '\0') { if(str[i] != ' ') { count += 1; } i++; } return count; } // function to calculate numbers of words int GetNumOfWords(string str) { int i = 0; int count = 1; while(str[i] != '\0') { if(str[i] == ' ' && str[i-1]...
I want flowchart process for this code c++ _____________________ #include<bits/stdc++.h> using namespace std; int main() {...
I want flowchart process for this code c++ _____________________ #include<bits/stdc++.h> using namespace std; int main() { char repeat = 'Y'; for (;repeat == 'Y';){ char empname[222]; float basicSalary, h_r_a, DearnessAllow, tax, netSalary; int e_id; cout<<"\nEmployee Name :"; cin>>empname; cout<<"\nEmployee Id :"; cin>>e_id; cout << "Enter Basic Salary : "; cin >> basicSalary; DearnessAllow = 0.30 * basicSalary; h_r_a= 800; switch (1) { case 1: if (basicSalary <= 2,50,000) tax = 0; case 2: if (basicSalary > 250000 && basicSalary <=...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; //...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; // constants const int FINAL_POSITION = 43; const int INITIAL_POSITION = -1; const int NUM_PLAYERS = 2; const string BLUE = "BLUE"; const string GREEN = "GREEN"; const string ORANGE = "ORANGE"; const string PURPLE = "PURPLE"; const string RED = "RED"; const string YELLOW = "YELLOW"; const string COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW}; const int NUM_COLORS = 6; // names...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT