对Vector内的结构体对象按照结构体内某成员进行排序

        首先定义一个结构体:

struct stu
{
    float y;
    int age;
    string name;
};

        然后定义一个比较函数,并返回布尔值。

bool comp(const struct stu & a, const struct stu & b)
{
    return a.age < b.age;
}

        这个是从小到大的排序。

vector<stu> vl;
for (size_t i = 0; i < 15; i++)
{
   left_stu.y = i*1.42;
   left_stu.age = 30-i;
   vl.push_back(left_stu);
}
sort(vl_stu.begin(), vl_stu.end(), comp);

遇到问题:当比较函数作为一个类的成员函数是需要加static

static bool comp1(const struct stu & a, const struct stu& b)
    {

        return a.age< b.age;
    }


版权声明:本文为jinking01原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。