悉野小楼

导航

c++ stl std::sort使用例子

例子1:
class User
{
public:
    int32_t m_fight_power;
private:
    int32_t m_level;
};

bool CenterData::compare(const User *left, const User *right)
{
    if(left->m_fight_power != right->m_fight_power)
    {
        return left->m_fight_power > right->m_fight_power;
    }
    return false;
}

typedef std::vector<User*> UserVector;
UserVector userVector;
std::sort(userVector.begin(), userVector.end(), compare);
例子2:
struct DamageData
{
    EntityUUID player_id;
    int64_t damage;
    std::string player_name;
};
bool compareDamage(const std::shared_ptr<DamageData> left, const std::shared_ptr<DamageData> right)
{
    if (left->damage != right->damage)
    {
        return (left->damage > right->damage);
    }
    return false;
}
vector<std::shared_ptr<DamageData>> ranks;
std::sort(ranks.begin(), ranks.end(), compareDamage);

 例子3:

struct FieldDescriptor {
    int point;
};
//functor 仿函数
struct FieldNumberSorter {
    bool operator()(FieldDescriptor* left, FieldDescriptor* right) {
        if (left->point > right->point)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};
int main()
{
    vector<const FieldDescriptor*> fields;
    std::sort(fields.begin(), fields.end(), FieldNumberSorter());
    system("pause");
    return 0;
}

 

posted on 2023-08-25 10:15  悉野  阅读(23)  评论(0编辑  收藏  举报