阅读量:2
在 C++ 的 set 容器中,你可以使用 find() 成员函数来判断一个元素是否已经存在。如果 find() 返回的迭代器等于 set 的 end() 迭代器,那么说明该元素不存在;否则,该元素存在于 set 中。
以下是一个示例代码:
#include
#include
using namespace std;
int main() {
set<int> my_set = {1, 2, 3, 4, 5};
int target = 6;
if (my_set.find(target) == my_set.end()) {
cout << target << " is not in the set." << endl;
} else {
cout << target << " is in the set." << endl;
}
return 0;
}
在这个示例中,我们创建了一个包含整数的 set,然后使用 find() 函数查找一个不存在的元素 6。因为 6 不在 set 中,所以 find() 返回的迭代器等于 set 的 end() 迭代器,我们输出 “6 is not in the set.”。
以上就是关于“c++ 中的 set 如何判断元素是否存在”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm