I have a function called FindMaxByArea that takes in a vector of Rectangle objects and returns one with the biggest length. When I compile my code I keep getting this error:
Rectangle.h:40:23: error: no match for call to ‘(AreaCompare) (const value_type&, const value_type&)’
if (isLessThan(arr[maxIndex], arr[i]))
~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
I am also not sure if appending {} to the end of AreaCompare is the correct way to call this function. Any suggestions would be appreciated.
return findMax(arr, AreaCompare{});
This is my Rectangle.h file
#pragma once
#ifndef Rectangle_H
#define Rectangle_H
#include <vector>
#include <iostream>
#include <functional>
using namespace std;
/*
Rectangle class
*/
class Rectangle
{
public:
int GetLength() const { return m_Length; }
int GetWidth() const { return m_Width; }
int getArea() const { return m_Length * m_Width; }
int getPerimeter() const { return (m_Width * 2) + (m_Length * 2); }
Rectangle(int length, int width) : m_Length(length), m_Width(width) {}
private:
int m_Length;
int m_Width;
};
/*
Function that takes in a vector and a compare function and
returns a generic with the largest properties
*/
template <typename Object, typename Comparator>
const Object & findMax(const vector<Object> & 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];
}
/*
A compare function that compares the area of two rectangles
*/
class AreaCompare
{
public:
bool isLessThan(const Rectangle &lhs, const Rectangle &rhs) const
{
return lhs.getArea() < rhs.getArea();
}
};
/*
A compare function that compares the perimeter of two rectangles
*/
class PerimeterCompare
{
public:
bool isLessThan(const Rectangle &lhs, const Rectangle &rhs) const
{
return lhs.getPerimeter() < rhs.getPerimeter();
}
};
/*
Function compares a vector of rectangles and returns one with
the largest area
*/
template <typename Object>
const Object & FindMaxByArea(const vector<Object> & arr)
{
return findMax(arr, AreaCompare{});
}
/*
Function compares a vector of rectangles and returns one with
the largest perimeter
*/
template <typename Object>
const Object & FindMaxByPerim(const vector<Object> & arr)
{
return findMax(arr, PerimeterCompare{});
}
#endif
main.cpp
#include <iostream>
#include <vector>
#include "Rectangle.h"
int main() {
vector<Rectangle> vec
{
Rectangle(1, 3),
Rectangle(4, 4)
};
cout << "Highest Area: " << FindMaxByArea(vec) << endl;
return 0;
}
FindMaxByArea? (What type is thearrparameter you're passing to it?)main.cpp.arris vector of Rectangles