一个有意思的C++泛型比较技巧文章

xiaoxiao2021-02-28  30

//2006-8-23 18:44 李国帅于网络收集 除了我感慨的编程者的技能之外,并无其他。 里面使用了构造函数,stl,泛型,重载运算符等技巧,虽然都是入门级技巧,不过能把它们灵活运用到一起实现一定目的,已经相当不容易。 /** * Example of Comparator, with rectangles. */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <vector> using namespace std; /** * A simple rectangle class. */ class Rectangle { public: //explicit用来防止由构造函数定义的隐式转换。 explicit Rectangle(int len = 0, int wid = 0) : length(len), width(wid) { } int getLength() const { return length; } int getWidth() const { return width; } void print(ostream & out = cout) const { out << "Rectangle " << getLength() << " by " << getWidth(); } private: int length; int width; }; ostream & operator<< (ostream & out, const Rectangle & rhs) { rhs.print(out); return out; } /** * Compare object: ordering by length. */ class LessThanByLength { public: bool operator( ) (const Rectangle & lhs, const Rectangle & rhs) const { return lhs.getLength() < rhs.getLength(); } }; /** * Compare object: ordering by area. */ class LessThanByArea { public: bool operator() (const Rectangle & lhs, const Rectangle & rhs) const { return lhs.getLength() * lhs.getWidth() < rhs.getLength() * rhs.getWidth(); } }; /** * Generic findMax, with a function object. * Precondition: a.size( ) > 0. */ template <class Object, class Comparator> const Object & findMax(const vector<Object> & a, Comparator isLessThan) { int maxIndex = 0; for (int i = 1; i < a.size(); i++) if (isLessThan(a[maxIndex], a[i])) maxIndex = i; return a[maxIndex]; } /** * main: create four rectangles. * find the max, two ways */ int main() { vector<Rectangle> a; a.push_back(Rectangle(1, 10)); a.push_back(Rectangle(10, 1)); a.push_back(Rectangle(5, 5)); a.push_back(Rectangle(4, 6)); //这是我添加的// cout << "push rectangles:" << endl; for (vector<Rectangle>::iterator it = a.begin(); it != a.end(); it++){ it->print(); cout << endl; } cout << "Largest length:\n\t" << findMax(a, LessThanByLength()) << endl; cout << "Largest area:\n\t" << findMax(a, LessThanByArea()) << endl; getchar(); return 0; }
转载请注明原文地址: https://www.6miu.com/read-1950166.html

最新回复(0)