

新闻资讯
技术学院必须提供比较规则,因为std::set基于红黑树需通过严格弱序维持有序和唯一性,内置类型有默认比较,自定义类需显式定义。
在C++中,若想将自定义类放入 std::set,必须提供一种方式让 set 能够比较两个对象的大小。因为 std::set 是基于红黑树实现的有序容器,元素插入时会自动排序,这就要求元素类型支持比较操作。
std::set 内部通过严格弱序(strict weak ordering)来组织元素,防止重复并保持有序。对于内置类型(如 int、double),默认有
最简单的方式是为类定义 operator。std::set 默认使用 less 示例:#include
#include
class Person {
public:
std::string name;
int age;
Person(std::string n, int a) : name(n), age(a) {}
// 重载 operator< 作为成员函数
bool operator<(const Person& other) const {
if (name != other.name) {
return name < other.name;
}
return age < other.age; // 姓名相同时按年龄排序
}
};
int main() {
std::set
people.insert(Person("Alice", 30));
people.insert(Person("Bob", 25));
people.insert(Person("Alice", 22));
for (const auto& p : people) {
std::cout << p.name << " " << p.age << std::endl;
}
return 0;
}
输出:
Alice 22
Alice 30
Bob 25
如果你不想修改类本身,或者想在不同场景下使用不同的排序规则,可以传入一个比较类作为 std::set 的模板参数。
示例:
class Person {
public:
std::string name;
int age;
Person(std::string n, int a) : name(n), age(a) {}
};
// 定义比较结构体
struct ComparePerson {
bool operator()(const Person& a, const Person& b) const {
if (a.age != b.age) {
return a.age < b.age;
}
return a.name < b.name;
}
};
std::set people;
此时排序优先按年龄,再按姓名。
不能直接把 lambda 当模板参数(除非泛型),但可以在运行时传入可调用对象。不过由于 set 模板需要类型,通常用 std::function 包装,但效率较低,不推荐用于性能敏感场景。
更实用的做法仍是使用仿函数或重载 operator
基本上就这些。只要提供明确的排序规则,自定义类就能顺利放进 std::set。选择哪种方式取决于你是否能修改类以及是否有多种排序需求。重载 operator