In this article we will discuss how to check if a given element exists in set or not.

Suppose we have a set of strings i.e.

Now we wnat to check if any given string exists in the set or not. Let’s do this using two different techniques i.e.

Search for an element in Set using set::find()

std::set provides a member function to find the existance of a given element in set i.e.

It accepts the element as argument and search for that in the set. If the element is found in set then it returns the iterator pointing to that element else it returns the iterator pointing to the end of set.

Let’s use set::find() function to check if “at” exists in above set or not i.e.

We can not modify the element pointed by this iterator because this element is used for indexing inside the set, changing it will make the indexing wrong. Therefore we can access the element through iterator but cannot modify it.

Search for an element in Set using set::count()

std::set provides a member function to find the occurrence count of a given element in set i.e.

It accepts the element as argument and search for its occurrence count in the set. As std::set can contain only unique elements, so occurrence count of the given element can be only 0 or 1 i.e,

If found then 1 else 0.

Let’s use set::count() function to check if “hello” exists in above set or not i.e.

Checkout the complete example as follows,

Output:

set::find() vs set::count()

Both set::find() and set:: count() helps to check the existence of an element in set. But why 2 different method for same thing ?

Complexity wise both find() and count() are same. Main difference is that set::find() returns the iterator of the given element. Iterator is useful if we have user define objects in set, instead of primitive data types.

As set::find() returns the iterator, We can perform operations on the object pointed by iterator, also we can modify the mutable content of that object

Suppose we have a struct Student i.e.

A Functor / Comparator, to compare Student objects using ID i.e.

Let’s Create a set of Student objects i.e.

Find a Student object with id 3 using set::find() and modify its name, because mName is mutable and can be modifies eve with const objects i.e.

Now search for an element with count() i.e.

We will not get any iterator with set::count(), so its not possible to perform any operation or modify content with count().

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.