I need to create a Rectangle class and then a findMax function which can compare
ID: 671571 • Letter: I
Question
I need to create a Rectangle class and then a findMax function which can compare an array of Rectangle objects and then return the max by area and then perimeter. Obviously, the way I have written it isn't working quite as expected. Any suggestions to get this to compile and run correctly.
#include
#include
#include
using namespace std;
template
const Object & findMax( const vector& arr, Comparator isLessThan ) {
int maxIndex = 0;
for( int i = 1; i < arr.size( ); ++i )
if( isLessThan( arr[ maxIndex ], arr[ i ]))
maxIndex = i;
return arr[ maxIndex ];
}
class Rectangle {
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 getPerimeter() const
{ return (2 * length) + (2 * width); }
double getArea() const
{ return length * width; }
};
class PeriCompare {
public:
bool operator()(const Rectangle & lhs, const Rectangle & rhs) const
{
return lhs.getPerimeter(), rhs.getPerimeter();
}
};
class AreaCompare {
public:
bool operator()(const Rectangle & lhs, const Rectangle & rhs) const
{
return lhs.getArea(), rhs.getArea();
}
};
int main()
{
vector rect = {Rectangle{2,3}, Rectangle{1,5}};
cout<<"Largest perimeter: "< cout<<"Largest area: "<
return 0;
}
Explanation / Answer
#include <iostream>
#include <vector>
using namespace std;
class Rectangle {
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 getPerimeter() const
{
return (2 * length) + (2 * width);
}
double getArea() const
{
return length * width;
}
};
class Comparator{
public:
virtual bool operator()(const Rectangle & lhs, const Rectangle & rhs) const
{
return false;
}
};
class PeriCompare : public Comparator{
public:
bool operator()(const Rectangle & lhs, const Rectangle & rhs) const
{
return lhs.getPerimeter() < rhs.getPerimeter();
}
};
class AreaCompare : public Comparator{
public:
bool operator()(const Rectangle & lhs, const Rectangle & rhs) const
{
return lhs.getArea() < rhs.getArea();
}
};
Rectangle findMax(const vector<Rectangle> &arr, Comparator *isLessThan){
int maxIndex = 0;
for (unsigned int i = 1; i < arr.size(); ++i){
if ((*isLessThan)(arr[maxIndex], arr[i])){
maxIndex = i;
}
}
return arr[maxIndex];
}
int main()
{
vector<Rectangle> rect = { Rectangle{ 2, 3 }, Rectangle{ 1, 5 } };
AreaCompare a;
cout << "Largest perimeter: " << findMax(rect, &PeriCompare()).getPerimeter() << endl;
cout << "Largest area: " << findMax(rect, &AreaCompare()).getArea() << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.