一个有意思的C++泛型比较技巧文章
2017-12-18 18:08
369 查看
//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; }
相关文章推荐
- C++ 传值 避免 内存泄漏的一个技巧。[new 了以后,不一定要delete][修正,new后一定delete,没人帮你释放的。我错了,此文章已没任何意义了]
- 一个无聊男人的疯狂《数据结构与算法分析-C++描述》学习笔记 习题2.8 随机数组的三种生成算法(补) 将bash的实现翻译成比较纯正的bash风格
- 一个比较有意思的C语言问题
- 一个比较有意思的判断两数大小的方法,不用逻辑比较运算符
- java编程思想总结10--泛型与 C++ 比较 (1)
- 一个比较有意思的算法题,猴子选大王
- 一个有意思的讲pci中断的文章
- 一个比较全的C++农历算法
- 转载一个比较有意思的程序函数,呵! result love(boy, girl)
- 深入理解 c# 第三章 用泛型方法将一个给定的值进行比较
- 一个字体,大小,颜色可定义的自绘静态框控件-XColorStatic 类(比较好看,一共19篇自绘文章)
- 一个比较有意思的项目,和微信有关的
- 3.3.3 以泛型方式将一个给定的值和默认值比较
- 记录一个Word操作技巧,很偏门的,鉴于Google很不方便用了,百度起来比较费劲所以记录一下
- 新看到一个C++博客,感觉文章还可以,留个记号
- 介绍一个个人博客中的几篇c++文章
- iteye一篇关于同步锁的一个比较不错的文章,入门用
- 一个比较全的C++农历算法
- 发现了一个比较有意思的url参数
- 在C++中如何定义一个行数和列数比较大的矩阵