How to check that an element is in a std::set?

前端 未结 10 2013
春和景丽
春和景丽 2020-11-30 17:13

How do you check that an element is in a set?

Is there a simpler equivalent of the following code:

myset.find(x) != myset.end()
10条回答
  •  余生分开走
    2020-11-30 17:27

    Another way of simply telling if an element exists is to check the count()

    if (myset.count(x)) {
       // x is in the set, count is 1
    } else {
       // count zero, i.e. x not in the set
    }
    

    Most of the times, however, I find myself needing access to the element wherever I check for its existence.

    So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end too.

    set< X >::iterator it = myset.find(x);
    if (it != myset.end()) {
       // do something with *it
    }
    

    C++ 20

    In C++20 set gets a contains function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245

    if (myset.contains(x)) {
      // x is in the set
    } else {
      // no x 
    }
    

提交回复
热议问题