阅读量:2
在 C++ 中,可以使用 std::set 容器来存储唯一元素
- 使用
find()成员函数:
#include
#include
int main() {
std::set<int> my_set = {1, 2, 3, 4, 5};
int target = 3;
auto it = my_set.find(target);
if (it != my_set.end()) {
std::cout << "Element " << target << " found in the set." << std::endl;
} else {
std::cout << "Element " << target << " not found in the set." << std::endl;
}
return 0;
}
- 使用
count()成员函数:
#include
#include
int main() {
std::set<int> my_set = {1, 2, 3, 4, 5};
int target = 3;
if (my_set.count(target) > 0) {
std::cout << "Element " << target << " found in the set." << std::endl;
} else {
std::cout << "Element " << target << " not found in the set." << std::endl;
}
return 0;
}
这两种方法都可以在 O(log n) 的时间复杂度内查找元素。find() 函数返回一个指向找到的元素的迭代器,如果未找到元素,则返回 end() 迭代器。count() 函数返回一个整数,表示元素在集合中出现的次数,如果元素不存在,则返回 0。
以上就是关于“c++ 中的 set 如何查找元素”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm