阅读量:97
在 C++ 中,std::set 是一个关联容器,它包含一组唯一的对象。默认情况下,std::set 使用 operator< 来比较元素,但你可以通过提供自定义的比较函数或自定义类型来实现不同的排序规则。
以下是如何在 C++ 中使用自定义类型作为 std::set 的元素:
- 定义自定义类型:
struct Person {
std::string name;
int age;
// 自定义比较函数
bool operator<(const Person& other) const {
if (name != other.name) {
return name < other class="hljs-keyword">return age < other>
- 使用自定义类型作为
std::set的元素:
#include
#include
int main() {
std::set people;
// 添加元素
people.insert(Person{"Alice", 30});
people.insert(Person{"Bob", 25});
people.insert(Person{"Charlie", 30});
// 遍历集合
for (const auto& person : people) {
std::cout << person class="hljs-string">": " << person class="hljs-keyword">return 0;
}
在这个例子中,我们定义了一个 Person 结构体,并重载了 < 运算符以便根据 name 和 age 对 Person 对象进行排序。然后,我们将 Person 对象插入到 std::set 中,并使用范围 for 循环遍历集合。
注意,由于我们自定义了比较函数,std::set 会根据 Person 对象的 name 和 age 属性对元素进行排序。在这个例子中,具有相同 name 的 Person 对象将根据其 age 属性进行排序。