在 C++ 中,std::set
是一个关联容器,它包含一组唯一的对象。要在 std::set
中执行查找操作,您可以使用迭代器或 std::find
算法。以下是两种方法的示例:
#include <iostream>
#include <set>
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 << "Found: " << *it << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
std::find
算法:#include <iostream>
#include <set>
#include <algorithm>
int main() {
std::set<int> my_set = {1, 2, 3, 4, 5};
int target = 3;
auto it = std::find(my_set.begin(), my_set.end(), target);
if (it != my_set.end()) {
std::cout << "Found: " << *it << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
在这两个示例中,我们首先创建了一个包含整数的 std::set
。然后,我们使用 find
方法查找目标值。如果找到了目标值,find
将返回一个指向该值的迭代器;否则,它将返回 my_set.end()
。我们可以使用此迭代器检查是否找到了目标值,并相应地输出结果。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:c++ 中的 set 如何进行集合过滤