一个有意思的C++泛型比较技巧文章
来源:互联网 发布:淘宝卖家优惠券链接 编辑:程序博客网 时间:2024/05/21 18:33
//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;}
阅读全文
0 0
- 一个有意思的C++泛型比较技巧文章
- 比较有意思的cvpr文章
- 一个比较有意思的宏
- 几个比较有意思的文章和网址
- 个人认为比较有意思的文章
- CNOUG 里比较有意思的一个SQL
- 一个腾讯的笔试题,比较有意思
- 一个比较有意思的评论留言
- 遇到一个比较有意思的NIO问题!
- 挺有意思的比较,JAVA与C#。
- C/C++一些比较有意思的算法
- 有意思的文章推荐
- 挺有意思的文章。。。
- 一个有意思的讲pci中断的文章
- 转一个mm的文章--兔子和狼,很有意思
- 比较有意思的指针
- 比较有意思的问题
- 比较有意思的地图
- 查看cuda和cudnn版本的命令
- js将图片转为base64编码 && js将base64编码图片转为Blob格式
- 截图字符串 获取匹配条件后的 最后一个
- JavaScript高级程序设计(第六章)——读书笔记
- 【NOI题解】 3.7数据结构之堆
- 一个有意思的C++泛型比较技巧文章
- JS维护nginx反向代理,妈妈再也不用担心我跨域了!
- 34岁!100天!学会Java编程(Day49-Day52)—OOP设计模式
- linux查看文件行号
- C语言作业(4)
- 机器学习理论 || GMM模型
- Mysql ERROR 1040 (HY000): Too many connections
- Android 反编译(四)了解.smail方法
- label设置字数超出不换行