C++ STL The compare function

来源:互联网 发布:深圳java自行车 编辑:程序博客网 时间:2024/06/04 18:04

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>());



0 0