If you wanted to search for an element in a std::set container, you can
invoke the std::set's find method. You pass to it the element value you
wanted to search for in the set, and this method returns an iterator to
the found element in the set.
And if the element was not found in the set, what will this method return?
Well, if you followed my previous course on sequential containers,
you know that the return value for the element not found case is the
end iterator. So, you can use an if statement like this to check
whether the input element was found in the set.
In addition,
if you wanted to access the set's element using the returned iterator,
you can dereference the iterator with this pointer‑like syntax,
*result. Note that a very cool thing about the set's find method is
its logarithmic runtime complexity.
This basically means that the performance of a set's find is very good.
So, using a std::set, you'll get very good lookup times.
On the other hand,
if you invoke the std::find algorithm on a container that is not sorted like
a generic std::vector, you get linear time performance,
which is definitely worse than logarithmic time.
If you're not familiar with topics like linear search or runtime
complexity, or you wanted to learn more, you can watch the module on
efficiently searching in my course on Introduction to Data Structures
and Algorithms in C++. In addition to invoking std::find, C++20 has
introduced a new convenient method to check whether a set contains a
given element.
Basically,
you can just invoke the set's contains method without dealing with
iterators at all. This will make your code much simpler and clearer if you
don't really need iterators for some other reason.
Okay,
after this theoretical introduction of std::set important
operations, let's take a look at some compatible C++ demo code
showing std::set in action in the next clip.