首先定义一个结构体:
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;
}
C++结构体排序与成员函数作为比较器

本文介绍了如何在C++中定义一个结构体,并使用成员函数作为比较器进行排序。示例展示了如何创建一个包含浮点数、整数和字符串的结构体,然后定义一个比较函数用于年龄从小到大排序。当比较函数是类的成员函数时,需要添加`static`关键字。示例中还给出了一个填充和排序结构体向量的代码片段。
728

被折叠的 条评论
为什么被折叠?



