std::set 判断两个元素关系 并删除其中一个元素 迭代器方法
时间: 2024-01-22 12:02:37 浏览: 26
在 std::set 中,判断两个元素的关系可以使用 set::find() 函数来查找元素。如果元素存在,则返回指向该元素的迭代器,否则返回指向 set 末尾的迭代器。利用这个特性可以判断两个元素是否相等。
删除 set 中的元素可以使用 set::erase() 函数,该函数接受一个迭代器参数,表示要删除的元素。在删除元素时需要注意,如果删除元素后迭代器失效,需要使用删除元素后返回的迭代器来更新当前迭代器。
以下是一个示例代码:
```c++
#include <iostream>
#include <set>
int main() {
std::set<int> s = {1, 2, 3};
// 查找元素
auto it1 = s.find(2);
auto it2 = s.find(4);
if (it1 != s.end()) {
std::cout << "元素 2 存在" << std::endl;
} else {
std::cout << "元素 2 不存在" << std::endl;
}
if (it2 != s.end()) {
std::cout << "元素 4 存在" << std::endl;
} else {
std::cout << "元素 4 不存在" << std::endl;
}
// 删除元素
auto it3 = s.find(1);
if (it3 != s.end()) {
s.erase(it3);
std::cout << "元素 1 已删除" << std::endl;
} else {
std::cout << "元素 1 不存在" << std::endl;
}
// 迭代器操作
for (auto it = s.begin(); it != s.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
元素 2 存在
元素 4 不存在
元素 1 已删除
2 3
```