溫馨提示×

c++ 中的 set 如何判斷元素是否存在

c++
小樊
154
2024-11-29 11:45:43
欄目: 編程語言

在 C++ 的 set 容器中,你可以使用 find() 成員函數來判斷一個元素是否已經存在。如果 find() 返回的迭代器等于 setend() 迭代器,那么說明該元素不存在;否則,該元素存在于 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() 返回的迭代器等于 setend() 迭代器,我們輸出 “6 is not in the set.”。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女