C++ STL The compare function
2015-09-19 08:46
465 查看
The Compare Function in STL of C++
There are many comparing functions used in the STL.There are 3 ways to implement the comparing function.
1. Using operation overloading to define <
1.1 Using own bool function
Define the element in STL like following:
struct T{ bool operator< (T other) const{ return weight < other.weight; } int index; int weight; };
NOTE: cannot missing const!
1.2 Using friend function
Define the element in STL like following:
struct T{ friend bool operator< (T a, T b){ return a.weight < b.weight; } int index; int weight; };
2. Using operator overloading to define ()
Using struct to reload ():
struct cmp{ bool operator () (T a, T b){ return a.weight < b.weight; } };
And make it as a parameter in STL algorithm.
sort(container.begin(), container.end(), cmp());
NOTE: cannot miss the latest ()
3. Directly using bool function without struct:
bool cmp(T a, T b) { return a.weight > b.weight; } sort(contain.begin(), container.end(), cmp);
NOTE: < is from little to large
> is from large to little
4. Some intern comparing functions in the head file of functional
include <functional>
equal_to<Type>
not_equal_to<Type> greater<Type>
greater_equal<Type> less<Type>
less_equal<Type>
Note: must add () when use
sort(begin, end, less<T>());
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解