Question

Convert the OrderedPair class, which is provided below, into a templated class. Note that it will...

Convert the OrderedPair class, which is provided below, into a templated class. Note that it will only work with types that have the operators + and < and << overloaded. But you should be able to try your templated class out with types string, MyString, double, FeetInches, Fraction, etc. I would encourage you to try these out.

Also, create a programmer-defined exception class named "DuplicateMemberError" and add an if statement to each of the two mutators to throw this exception if the precondition has not been met. The precondition is given as a comment in the header file. Notice that you can test your exception handling by entering the same number twice when prompted for two numbers.

Put your class in a namespace named "cs_pairs"

Finally, to show that your class will work with different types, and also to show that you know how to code a client that uses the templated class, modify the given client file so that it uses your class using int as the type parameter, and then, in the same main(), repeat the code again with a few changes necessary to make it use ordered pairs of Strings instead of ordered pairs of ints. One of the things you'll have to change is the generation of the random values for the ordered pairs. Here's what I used:

    string empty = "";
    myList2[i].setFirst(empty + char('a' + rand() % 26));
    myList2[i].setSecond(empty + char('A' + rand() % 26));

Here is the header file, orderedpair.h. The syntax for declaring a constant in a class may look mysterious. To use constants in a class, we have to declare it inside the class, then assign it a value outside the class, as you'll see below. (That's actually not true for int constants -- they can be assigned inside the class -- but we want our code to be flexible enough to handle different types.)

#include 

/* precondition for setFirst and setSecond: the values of first and second cannot be equal, 
except when they are both equal to DEFAULT_VALUE.
*/


namespace cs_pairs {
    class OrderedPair {
        public:
            // Use the first of the following two lines to make the non-templated version work.
            // Switch to the second one when you begin converting to a templated version.
            
            static const int DEFAULT_VALUE = int();
            // static const int DEFAULT_VALUE;

            OrderedPair(int newFirst = DEFAULT_VALUE, int newSecond = DEFAULT_VALUE);
            void setFirst(int newFirst);
            void setSecond(int newSecond);
            int getFirst() const;
            int getSecond() const;
            OrderedPair operator+(const OrderedPair& right) const;
            bool operator<(const OrderedPair& right) const;
            void print() const;
        private:
            int first;
            int second;
    };


    // Leave the following const declaration commented out when you are testing the non-templated
    // version. Uncomment it when you begin converting to a templated version.  
    // The templated version will require a template prefix as well as some minor edits to the code.
    
    // const int OrderedPair::DEFAULT_VALUE = int();

}


Here is the implementation file, orderedpair.cpp

#include "orderedpair.h"
#include 
using namespace std;

namespace cs_pairs {
    OrderedPair::OrderedPair(int newFirst, int newSecond) {
        setFirst(newFirst);
        setSecond(newSecond);
    }

    void OrderedPair::setFirst(int newFirst) {
    // if statement to throw an exception if precondition not met goes here.        
        first = newFirst;
    }

    void OrderedPair::setSecond(int newSecond) {
    // if statement to throw an exception if precondition not met goes here.    
        second = newSecond;
    }

    int OrderedPair::getFirst() const {
        return first;
    }

    int OrderedPair::getSecond() const {
        return second;
    }

    OrderedPair OrderedPair::operator+(const OrderedPair& right) const {
        return OrderedPair(first + right.first, second + right.second);
    }


    bool OrderedPair::operator<(const OrderedPair& right) const {
        return first + second < right.first + right.second;
    }


    void OrderedPair::print() const {
        cout << "(" << first << ", " << second << ")";
    }
}

Here is the client file.

#include 
#include 
#include 
#include "orderedpair.h"
using namespace std;
using namespace cs_pairs;





int main() {
    int num1, num2;
    OrderedPair myList[10];
    
    srand(static_cast(time(0)));
    cout << "default value: ";
    myList[0].print();
    cout << endl;
    
    for (int i = 0; i < 10; i++) {
        myList[i].setFirst(rand() % 50);
        myList[i].setSecond(rand() % 50 + 50);
    }
    
    myList[2] = myList[0] + myList[1];
    
    if (myList[0] < myList[1]) {
        myList[0].print();
        cout << " is less than ";
        myList[1].print(); 
        cout << endl;
    }
    
    for (int i = 0; i < 10; i++) {
        myList[i].print();
        cout << endl;
    }
    
    cout << "Enter two numbers to use in an OrderedPair.  Make sure they are different numbers: ";
    cin >> num1 >> num2;
    OrderedPair x;
    
    /* use this before you've implemented the exception handling in the class:
    */
    
    x.setFirst(num1);
    x.setSecond(num2);
    
    /* use this after you've implemented the exception handling in the class:
    try {
        x.setFirst(num1);
        x.setSecond(num2);
    } catch (OrderedPair::DuplicateMemberError e) {
        x.setFirst(OrderedPair::DEFAULT_VALUE);
        x.setSecond(OrderedPair::DEFAULT_VALUE);        
    }
    */
    
    cout << "The resulting OrderedPair: ";
    x.print();
    cout << endl;
}

/*The variables should be a different type*/

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Editable code:

File name: “orderedpairs.h

//Define the header file

#ifndef ORDERED_PAIR_H

#define ORDERED_PAIR_H

//Include the necessary header files

#include <iostream>

#include <exception>

#include <stdexcept>

/*Declaration of class name "cs_pairs" in a namespace*/

namespace cs_pairs

{

//Template class

template <class T>

//Define the class "orderedPair"

class orderedPair

{

//Access specifier

public:

/*Define the exception class named "DuplicateMemberError"*/

class DuplicateMemberError : public std::exception

{

//Access specifier

public:

//Constant exception

const char * what () const throw();

};

//Default value

static const T DEFAULT_VALUE;

//Method declaration

orderedPair(T newFirst = DEFAULT_VALUE, T newSecond = DEFAULT_VALUE) throw(DuplicateMemberError);

//Method declaration

void setFirst(T newFirst) throw(DuplicateMemberError);

//Method declaration

void setSecond(T newSecond) throw(DuplicateMemberError);

//Method declaration

T getFirst();

//Method declaration

T getSecond();

//Method declaration

orderedPair operator+(const orderedPair& right);

//Method declaration

bool operator<(const orderedPair& right);

//Method declaration

void print();

//Access specifier

private:

//Declaration of class variables

T first;

T second;

};

}

#endif

File name: “orderedPair.cpp

//Include the header file

#include "orderedpairs.h"

//Delaration of namespace

using namespace std;

/*Declaration of class name "cs_pairs" in a namespace*/

namespace cs_pairs

{

//Template class

template <class T>

//Define the method "orderedPair()"

orderedPair<T>::orderedPair(T newFirst, T newSecond) throw(DuplicateMemberError)

{

//Declare the method "setFirst()"

setFirst(newFirst);

//Declare the method "setSecond()"

setSecond(newSecond);

}

//Template class

template <class T>

//Define the method "setFirst()"

void orderedPair<T>::setFirst(T newFirst) throw(DuplicateMemberError)

{

//Check the condition

if(newFirst == second && newFirst != DEFAULT_VALUE)

{

//True, throw the error

throw DuplicateMemberError();

}

//Otherwise, assign the value into "first"

first = newFirst;

}

//Template class

template <class T>

//Define the method "setSecond()"

void orderedPair<T>::setSecond(T newSecond) throw(DuplicateMemberError)

{

//Check the condition

if(newSecond == first && newSecond != DEFAULT_VALUE)

{

//True, throw the error

throw DuplicateMemberError();

}

//Otherwise, assign the value into "second"

second = newSecond;

}

//Template class

template <class T>

//Define the method "getFirst()"

T orderedPair<T>::getFirst()

{

//Return the value

return first;

}

//Template class

template <class T>

//Define the method "getSecond()"

T orderedPair<T>::getSecond()

{

//Return the value

return second;

}

//Template class

template <class T>

//Method definition

orderedPair<T> orderedPair<T>::operator+(const orderedPair& right)

{

//Return the value

return orderedPair(first + right.first, second + right.second);

}

//Template class

template <class T>

//Method definition

bool orderedPair<T>::operator<(const orderedPair& right)

{

//Return the value

return first + second < right.first + right.second;

}

//Template class

template <class T>

//Define the method "print()"

void orderedPair<T>::print()

{

//Print statement

cout << "(" << first << ", " << second << ")";

}

//Template class

template <class T>

const char * orderedPair<T>::DuplicateMemberError::what() const throw()

{

//Return the value

return "duplicate member";

}

//Template class

template <class T>

//Declaration of default value

const T orderedPair<T>::DEFAULT_VALUE = T();

//Declaration of template class out with string

template class orderedPair<string>;

}

File name: “main.cpp

//Include necessary header files

#include <iostream>

#include <stdlib.h>

#include "orderedpairs.h"

//Delaration of namespace

using namespace std;

using namespace cs_pairs;

//Define the "main()" method

int main()

{

//Variable declaration

string num1, num2;

//Array declaration

orderedPair<string> myList[10];

//Variable initialization

string empty = "";

//Print statement

cout << "default value: ";

//Call the method "print()"

myList[0].print();

//New line

cout << endl;

/*Iterate value until the condition becomes true*/

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

{

myList[i].setFirst(empty + char('a' + rand() % 13));

myList[i].setSecond(empty + char('n' + rand() % 13));

}

//Assign the value into "myList[2]"

myList[2] = myList[0] + myList[1];

//Check the condition

if (myList[0] < myList[1])

{

//Call the method "print()"

myList[0].print();

//Print statement

cout << " is less than ";

//Call the method "print()"

myList[1].print();

//New line

cout << endl;

}

/*Iterate value until the condition becomes true*/

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

{

//Call the method "print()"

myList[i].print();

//New line

cout << endl;

}

//Print statement

cout << "Enter two strings to use in an orderedPair. Make sure they are different strings: ";

//Get the value from the user

cin >> num1 >> num2;

//Object creation

orderedPair<string> x;

//Try block

try

{

//Call the method "setFirst()"

x.setFirst(num1);

//Call the method "setSecond()"

x.setSecond(num2);

}

//Catch block

catch (orderedPair<string>::DuplicateMemberError &e)

{

//Call the method "setFirst()"

x.setFirst(empty);

//Call the method "setSecond()"

x.setSecond(empty);

}

//Print statement

cout << "The resulting orderedPair: ";

//Call the method "print()"

x.print();

//New line

cout << endl;

}

Add a comment
Know the answer?
Add Answer to:
Convert the OrderedPair class, which is provided below, into a templated class. Note that it will...
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
  • C++ I am using visual studio for it. Make a copy of the Rational class you...

    C++ I am using visual studio for it. Make a copy of the Rational class you created in the previous Lab. Modify the class. Replace all your mathematical, input, and output functions with overloaded operators. Overload the following 12 operators: + - * / < > = = ! = <= >= >> << In order to test your class in your main function, prompt the user for a numerator and a denominator for your first object. Repeat the prompt...

  • NEED ASAP PLEASE HELP Task: --------------------------------------------------------------------------------------...

    NEED ASAP PLEASE HELP Task: --------------------------------------------------------------------------------------------------------------------------------- Tasks to complete: ---------------------------------------------------------------------------------------------------------------------------------------- given code: ----------------------------------------------------------------------------------------------------------------------------------------------- main.cpp #include <iostream> #include <iomanip> #include "fractionType.h" using namespace std; int main() { fractionType num1(5, 6); fractionType num2; fractionType num3; cout << fixed; cout << showpoint; cout << setprecision(2); cout << "Num1 = " << num1 << endl; cout << "Num2 = " << num2 << endl; cout << "Enter the fraction in the form a / b: "; cin >> num2; cout << endl; cout <<...

  • May i ask for help with this c++ problem? this is the code i have for assignment 4 question 2: #...

    may i ask for help with this c++ problem? this is the code i have for assignment 4 question 2: #include<iostream> #include<string> #include<sstream> #include<stack> using namespace std; int main() { string inputStr; stack <int> numberStack; cout<<"Enter your expression::"; getline(cin,inputStr); int len=inputStr.length(); stringstream inputStream(inputStr); string word; int val,num1,num2; while (inputStream >> word) { //cout << word << endl; if(word[0] != '+'&& word[0] != '-' && word[0] != '*') { val=stoi(word); numberStack.push(val); // cout<<"Val:"<<val<<endl; } else if(word[0]=='+') { num1=numberStack.top(); numberStack.pop(); num2=numberStack.top(); numberStack.pop();...

  • How convert this c++ into C #include<iostream> #include <stdlib.h> using namespace std; void multiplication() { int...

    How convert this c++ into C #include<iostream> #include <stdlib.h> using namespace std; void multiplication() { int num1; int c, num2, ans; cout<<"Enter difficulty level(1/2)\n"; cin>>c; if(c==1) { num1= rand() % 10; num2= rand() % 10; cout<<"what is"<<num1 <<"*"<<num2<<"?\n" ; cin>>ans while(ans!=(num1*num2)) { if(ans!=(num1*num2)) { cout<< "No. Please try again.\n"; cout<<"what is"<<num1 <<"*"<<num2<<"?\n" ; cin>>ans; } } } else if(c==2) { num1= rand() % 10+90; num2= rand() % 10+90; cout<<"what is"<<num1 <<"*"<<num2<<"?\n" ; cin>>ans; while(ans!=(num1*num2)) { if(ans!=(num1*num2)) { cout<< "No. Please...

  • How to convert C++ code to C #include<iostream> #include <stdlib.h> using namespace std; void multiplication() {...

    How to convert C++ code to C #include<iostream> #include <stdlib.h> using namespace std; void multiplication() { int num1; int c, num2, ans; cout<<"Enter difficulty level(1/2)\n"; cin>>c; if(c==1) { num1= rand() % 10; num2= rand() % 10; cout<<"what is"<<num1 <<"*"<<num2<<"?\n" ; cin>>ans while(ans!=(num1*num2)) { if(ans!=(num1*num2)) { cout<< "No. Please try again.\n"; cout<<"what is"<<num1 <<"*"<<num2<<"?\n" ; cin>>ans; } } } else if(c==2) { num1= rand() % 10+90; num2= rand() % 10+90; cout<<"what is"<<num1 <<"*"<<num2<<"?\n" ; cin>>ans; while(ans!=(num1*num2)) { if(ans!=(num1*num2)) { cout<< "No....

  • I need assistance with the C++ code below to remove the "this" pointers while maintaining the...

    I need assistance with the C++ code below to remove the "this" pointers while maintaining the code's current output and functionality. Also, there should be a private class in the header file, but I'm not sure what I should include there. Any help would be greatly appreciated! ***main.cpp driver file*** #include <iostream> #include "vector.h" using namespace std; int main() {   vectorInfo v1(7, 6);   vectorInfo v2(5, 4);       v1.set(3, 2);   cout << "v1 : ";   v1.print();       cout << "v2 :...

  • SEE THE Q3 for actual question, The first Two are Q1 and Q2 answers . Q1...

    SEE THE Q3 for actual question, The first Two are Q1 and Q2 answers . Q1 #include<iostream> using namespace std; // add function that add two numbers void add(){    int num1,num2;    cout << "Enter two numbers "<< endl;    cout << "First :";    cin >> num1;    cout << "Second :";    cin >>num2;    int result=num1+num2;    cout << "The sum of " << num1 << " and "<< num2 <<" is = "<< result;   ...

  • I'm kind of new to programming, and I am having trouble figuring out why my program...

    I'm kind of new to programming, and I am having trouble figuring out why my program isn't running. Below is the code that I wrote for practice. I will comment where it says the error is. So the error that I'm getting is "error: no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream<char>}' ". I'm not sure why I'm getting this because I added the library <iostream> at the top. Thank you. Code: #include <iostream> using namespace std; class...

  • ////****what am i doing wrong? im trying to have this program with constructors convert inches to...

    ////****what am i doing wrong? im trying to have this program with constructors convert inches to feet too I don't know what im doing wrong. (the program is suppose to take to sets of numbers feet and inches and compare them to see if they are equal , greater, less than, or not equal using operator overload #include <stdio.h> #include <string.h> #include <iostream> #include <iomanip> #include <cmath> using namespace std; //class declaration class FeetInches { private:    int feet;   ...

  • I cannot get the C++ code below to compile correctly. Any assistance would be greatly appreciated!...

    I cannot get the C++ code below to compile correctly. Any assistance would be greatly appreciated! ***main.cpp driver file*** #include #include #include "vector.h" using namespace std; int main() {     vectorInfo v1(3, -1);     vectorInfo v2(2, 3);     cout << "v1 : ";     v1.print();     cout << "v2 : ";     v2.print();     cout << "v1 magnitude : " << v1.magnitude() << endl;     cout << "v1 direction : " << v1.direction() << " radians" << endl;     cout...

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