在 C++ 中,你可以使用 std::set
容器中的 find()
成員函數來判斷一個元素是否存在于集合中。如果 find()
函數返回的迭代器等于 end()
迭代器,說明該元素不存在;否則,表示元素存在于集合中。
以下是一個示例:
#include <iostream>
#include <set>
int main() {
std::set<int> my_set = {1, 2, 3, 4, 5};
int target = 3;
if (my_set.find(target) != my_set.end()) {
std::cout << target << " 存在于集合中" << std::endl;
} else {
std::cout << target << " 不存在于集合中" << std::endl;
}
return 0;
}
在這個示例中,我們創建了一個包含整數的 std::set
,然后使用 find()
函數查找目標值 3
。如果 find()
返回的迭代器不等于 end()
,我們輸出目標值存在于集合中;否則,輸出目標值不存在于集合中。