Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Define a Rectangle class that provides getLength and getWidth. Write a main that

ID: 3786698 • Letter: D

Question

Define a Rectangle class that provides getLength and getWidth. Write a main that creates a vector of Rectangles and finds the largest Rectangle on the basis of area. For this part of the assignment, you need to submit a separate .cpp file as well as a screenshot in your HWK submission indicating successful testing of the code. No credit will be given for code that does not compile or segfaults. Hint: Essentially, you want to tweak the Square class code of Figure 1.23, which is provided on Blackboard.

Explanation / Answer

main.cpp

#include <iostream>

#include "findmax.h"

#include <vector>

using std::vector;

using std::ostream;

using std::cout;

class Rectangle {

private:

    double length;

    double width;

public:

    explicit Rectangle( double l = 0.0, double w = 0.0 ): length{ l }, width{ w } { }

    double getLength( ) const{

      return length;

    }

    double getWidth( ) const{

      return width;

    }

    double getArea( ) const{

      return (length * width);

    }

    double getPerimeter( ) const{

      return (length + length + width + width);

    }

    void print( ostream & out = cout ) const{

      out << "(Rect, len: " << length << ", width: " << width;

    }

    bool operator< (const Rectangle & rhs) const{

      if (getArea() != rhs.getArea()){

        return (getArea() < rhs.getArea());

      } else {

        return (getPerimeter() < rhs.getPerimeter());

      }

    }

};

ostream & operator<< (ostream & out, const Rectangle& rhs){

rhs.print(out);

return out;

}

int main(){

vector<Rectangle> v = {Rectangle{2.0,4.0}, Rectangle{3.0,3.0}, Rectangle{8.0,1.0}, Rectangle{4.0,2.25}};

cout << "Largest Rect: " << findMax(v) << std::endl;

return 0;

}

findMax.h

#ifndef FINDMAX_H

#define FINDMAX_H

#include <vector>

using std::vector;

template <typename Comparable>

const Comparable & findMax( const vector<Comparable> & a ){

int maxIndex = 0;

for (int i = 1; i < a.size(); ++i){

    if (a[maxIndex] < a[i]){

      maxIndex = i;

    }

}

return a[maxIndex];

}

#endif

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote