パープルハット

※当サイトではGoogleアドセンス広告を利用しています

C++ set 要素の存在確認(find, count, contains)


setにおいて要素の存在を確認する方法について

キーの存在を確認する方法には主に次の3つの関数を使った方法があります。

  1. set::contains(C++20以降)
  2. set::count
  3. set::find

数字が小さいものほど使いやすいですが、1のcontainsはC++20以降でしか使えないという問題があります。
以降では、stをset型変数とします




1. set::containsを使った方法(C++20以降)

参考:set::contains - cpprefjp C++日本語リファレンス
st.contains(n)をすると、

  • true:nがst内に存在
  • false :nは存在しない

となるので、要素の存在を確認できます。
C++20以降の機能のようなので、コンパイラのバージョンに注意。

ソースコード

#include <iostream>
#include <set>

int main()
{
    std::set<int> st{ 1, 3, 5, 7 };

    // 「1」があるか 
    if (st.contains(1)) {
        std::cout << "1が存在" << std::endl;
    }
    else {
        std::cout << "1はない" << std::endl;
    }

    //「2」があるか 
    if (st.contains(2)) {
        std::cout << "2が存在" << std::endl;
    }
    else {
        std::cout << "2はない" << std::endl;
    }
}

実行結果

1が存在
2はない





2. set::countを使う場合

参考:set::count - cpprefjp C++日本語リファレンス

  • st.count(n)をすると、stに含まれるnの個数が取得できます。
  • setは同一の要素は保持しないので、nがst内にある時st.count(n)=1、存在しないときは0になると言い換えられます。
  • if文の条件式は、非ゼロのときに処理を行うので、「if(st.count(n))」でnが存在するときの条件分岐ができます。

ソースコード

#include <iostream>
#include <set>

int main()
{
    std::set<int> st{ 1, 3, 5, 7 };

    // 「1」があるか 
    if (st.count(1)) {
        std::cout << "1が存在" << std::endl;
    }
    else {
        std::cout << "1はない" << std::endl;
    }

    //「2」があるか 
    if (st.count(2)) {
        std::cout << "2が存在" << std::endl;
    }
    else {
        std::cout << "2はない" << std::endl;
    }
}

実行結果

1が存在
2はない





3. set::findを使う場合

参考:set::find - cpprefjp C++日本語リファレンス
st.find(n) != st.end()について、

  • true:nがある
  • false :nがない

とnの存在を調べることができます。

ソースコード

#include <iostream>
#include <set>

int main()
{
    std::set<int> st{ 1, 3, 5, 7 };

    // 「1」があるか 
    if (st.find(1) != st.end()) {
        std::cout << "1が存在" << std::endl;
    }
    else {
        std::cout << "1はない" << std::endl;
    }

    //「2」があるか 
    if (st.find(2) != st.end()) {
        std::cout << "2が存在" << std::endl;
    }
    else {
        std::cout << "2はない" << std::endl;
    }
}

実行結果

1が存在
2はない