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

前端 未结 10 1984
春和景丽
春和景丽 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:42

    Just to clarify, the reason why there is no member like contains() in these container types is because it would open you up to writing inefficient code. Such a method would probably just do a this->find(key) != this->end() internally, but consider what you do when the key is indeed present; in most cases you'll then want to get the element and do something with it. This means you'd have to do a second find(), which is inefficient. It's better to use find directly, so you can cache your result, like so:

    auto it = myContainer.find(key);
    if (it != myContainer.end())
    {
        // Do something with it, no more lookup needed.
    }
    else
    {
        // Key was not present.
    }
    

    Of course, if you don't care about efficiency, you can always roll your own, but in that case you probably shouldn't be using C++... ;)

提交回复
热议问题