在 C++ 的 set 容器中,你可以使用 find() 成員函數來判斷一個元素是否已經存在。如果 find() 返回的迭代器等于 set 的 end() 迭代器,那么說明該元素不存在;否則,該元素存在于 set 中。
以下是一個示例代碼:
#include <iostream>
#include <set>
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.”。