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()
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()
I use
But it is not as efficient as
My version only saves my time in writing the code. I prefer it this way for competitive coding.
If you were going to add a
contains
function, it might look like this:This works with
std::set
, other STL containers, and even fixed-length arrays:Edit:
As pointed out in the comments, I unintentionally used a function new to C++0x (
std::begin
andstd::end
). Here is the near-trivial implementation from VS2010:You can also check whether an element is in set or not while inserting the element. The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.
For example: Suppose the set already has 20 as an element.
If the element is newly inserted than pair::first will point to the position of new element in set.
I was able to write a general
contains
function forstd::list
andstd::vector
,This cleans up the syntax a bit.
But I could not use template template parameter magic to make this work arbitrary stl containers.
Any comments about improving the last answer would be nice.
The typical way to check for existence in many STL containers is:
Another way of simply telling if an element exists is to check the
count()
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.