In this article we will discuss different ways to find or search a given element in the list.

std::list does not provide ant find() or contains() method. So, if we want to search for an element in list or check if an element exists in std::list, then we not to write some code for it i.e.

Logic Used to find a given element in list,

  • Iterate over all the elements of list
    • For each element check if this element is equal to given element

Suppose we have a list of strings i.e.

Now if we want to check if ‘the’ exists in this list or not. Let’s see different ways to do this,

Searching an element in std::list using std::find()


STL Provides an algorithm std::find() i.e.

In std::find() you can pass two iterators and a value. It will iterate all the elements between 2 given iterators and compare the given val with each one.
If any match is found, then it will immediately return that iterator, else it returns the iterator pointing to end of list.

Let’s see how to find a string in std::list using std::find

Complete example is as follows,


Generic contains() method for std::list

Let’s create a generic function template that checks for the given value of type T in std::list<T>.

It will work for any type of list i.e. list of int, string etc.

Using generic contains with list of int,

Using generic contains with list of string,

Complete example is as follows,


To compile the above examples in Linux use following command,

g++ –std=c++11 example.cpp

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.