I don't mind using a vector, especially if you want to be able to store duplicate elements. By using a simple lambda function, we can sort the objects by whatever member of a Rect we want. In this example, I chose to sort Rect objects by area.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Rect {
Rect(double height, double width, double area) {
_height = height;
_width = width;
_area = area;
}
double area() const {
return _area;
}
// sorts Rect objects by ascending order of area
static void sort_by_area(vector<Rect> &shapes) {
sort(shapes.begin(), shapes.end(), [](const Rect &first, const Rec &second)
{ return first.area() < second.area); });
}
private:
double _height;
double _width;
double _area;
};
int main() {
vector<Rect> r;
r.push_back(Rect(0,0,3));
r.push_back(Rect(0,0,2));
r.push_back(Rect(0,0,4));
for(auto &obj : r) {
//prints 3 2 4
cout << obj.area() << endl;
}
Rect::sort_by_area(r);
for(auto &obj : r) {
//prints 2 3 4
cout << obj.area() << endl;
}
return 0;
}