您的位置:首页 > 编程语言 > C语言/C++

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++