1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <sstream>
using namespace std;
class Rectangle
{
private:
int length_;
int width_;
public:
Rectangle(int l, int w) : length_(l), width_(w) {}
int length() const { return length_; }
int width() const { return width_; }
int area() const { return length_ * width_; }
};
ostream& operator<<(ostream& os, Rectangle const& r)
{
return os << r.length() << " x " << r.width();
}
bool operator > (Rectangle const& lhs, Rectangle const& rhs)
{
return lhs.area() > rhs.area();
}
//a templated function to print a container of any type
template <typename T>
void print(T const& c, string const& container)
{
cout << "Printing " << container << ": ";
for (auto x : c)
cout << x << ", ";
cout << endl;
}
//a binary function to be used with sort
template<typename T>
/*bool isGreaterThan(int lhs, int rhs)
{
return lhs > rhs;
}*/
bool isGreaterThan(T lhs, T rhs)
{
return lhs > rhs;
}
int main()
{
//5. sort a vector of Rectangles in descending order
vector<Rectangle> vr;
for (int i = 1; i <= 10; ++i)
{
Rectangle r{ i, i + 5 };
vr.push_back(r);
}
print(vr, "Rectangle vector");
sort(vr.begin(), vr.end(), isGreaterThan<Rectangle>);
//use a lambda to count how many Rectangles have area's greater than 50
int val = 0;
count_if(vr.begin(), vr.end(),
[&val](Rectangle const&r) {return (r.area() > 50) ? ++val : val; });
}
|