c++如何判断一个元素在一个集合里
时间: 2024-03-09 16:46:34 浏览: 32
在 C++ 中,可以使用 STL 中的 set 容器来表示集合。set 容器内部会自动对元素进行排序,并且不允许重复元素存在。
要判断一个元素是否在一个 set 集合中,可以使用 set 容器中的 find() 函数。find() 函数会返回一个指向要查找元素的迭代器,如果找不到,则返回一个指向集合尾部的迭代器。
以下是一个示例代码:
```
#include <iostream>
#include <set>
int main() {
std::set<int> mySet = {1, 2, 3, 4, 5};
// 判断元素 3 是否在 mySet 中
if (mySet.find(3) != mySet.end()) {
std::cout << "元素 3 存在于 mySet 中" << std::endl;
} else {
std::cout << "元素 3 不存在于 mySet 中" << std::endl;
}
// 判断元素 6 是否在 mySet 中
if (mySet.find(6) != mySet.end()) {
std::cout << "元素 6 存在于 mySet 中" << std::endl;
} else {
std::cout << "元素 6 不存在于 mySet 中" << std::endl;
}
return 0;
}
```
输出结果为:
```
元素 3 存在于 mySet 中
元素 6 不存在于 mySet 中
```