阅读量:2
在 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.name;
}
return age < other.age;
}
};
- 使用自定义类型作为
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.name << ": " << person.age << std::endl;
}
return 0;
}
在这个例子中,我们定义了一个 Person 结构体,并重载了 < 运算符以便根据 name 和 age 对 Person 对象进行排序。然后,我们将 Person 对象插入到 std::set 中,并使用范围 for 循环遍历集合。
注意,由于我们自定义了比较函数,std::set 会根据 Person 对象的 name 和 age 属性对元素进行排序。在这个例子中,具有相同 name 的 Person 对象将根据其 age 属性进行排序。
以上就是关于“c++ 中的 set 如何处理自定义类型”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm