C++ STL The compare function

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值