C++ list get element – C++ List – Find | Contains : How to Search an Element in std::list ?

C++ list get element: In the prior tutorials, we have discussed Different Ways to iterate over a List of objects in C++. Now, we have come up with a new tutorial on C++ concept ie., how to Search an Element in std::list in C++ Program.

std::find in C++

C++ std list example: C++ std::find function obtains the element in the given range of numbers. Also, it returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last.

Template of the Function

InputIterator find (InputIterator first, InputIterator last, const T& val)

first,last:
Input iterators to the initial and final positions in a sequence. The range
searched is [first,last), which contains all the elements between first and
last, including the element pointed by first but not the element pointed by last.

val:
Value to be search in the range

Return Value:
An iterator to the first element in the range that compares equal to val.
If no elements match, the function returns last.

Examples:

Input : 10 20 30 40
Output : Element 30 found at position : 2 (counting from zero)  

Input : 8 5 9 2 7 1 3 10
Output : Element 4 not found.
// CPP program to illustrate 
// std::find
// CPP program to illustrate 
// std::find
#include<bits/stdc++.h>
  
int main ()
{
    std::vector<int> vec { 10, 20, 30, 40 };
      
    // Iterator used to store the position 
    // of searched element
    std::vector<int>::iterator it;
      
    // Print Original Vector
    std::cout << "Original vector :";
    for (int i=0; i<vec.size(); i++)
        std::cout << " " << vec[i];
          
    std::cout << "\n";
      
    // Element to be searched
    int ser = 30;
      
    // std::find function call
    it = std::find (vec.begin(), vec.end(), ser);
    if (it != vec.end())
    {
        std::cout << "Element " << ser <<" found at position : " ;
        std::cout << it - vec.begin() << " (counting from zero) \n" ;
    }
    else
        std::cout << "Element not found.\n\n";
          
    return 0;
}

Output: 

Original vector : 10 20 30 40
Element 30 found at position : 2 (counting from zero)

Find and  Contains: How to Search an Element in std::list?

Std find c++: In this article we are going to see multiple ways we can search an element inside a list.

As there are no methods available in the std::list to find an element we are going to manually iterate over the array and check if any of the elements matches ours.

By using std::find() to search an element in std::list :

std::find c++: The standard library has an algorithm find( )function.

Syntax:

<class InputIterator, class T>

InputIterator find (InputIterator first, InputIterator last, const T& val);

C++ std list: In the find( ) function, we can pass two iterators and a value with them. The function will check all the elements given between them and compare it with the value we have provided.

If a match is found it returns the iterator or else it would return the iterator pointing to the list end.

Program to search an element in std list using std find()

Let’s see the below program to understand the use of find()function.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>
int main()
{
    std::list<std::string> stringList = {
        "I", "am",
        "the", "yes",
        "hey", "from"};

    // Create a Iterator for the list
    std::list<std::string>::iterator it;
    //Check for 'hey' inside the list
    it = std::find(stringList.begin(), stringList.end(), "hey");
    //Check if the iterator points to the end of the list
    if (it != stringList.end())
    {
        //If it does not point to end then the element exists
        std::cout << "'hey' exists in list " << std::endl;
    }
    else
    {
        //If it points to end, then the element does not exist
        std::cout << "'hey' not there" << std::endl;
    }
}
Output :
'hey' exists in list

By using generic contains() method for std::list :

C++ std find: Let’s create a generic contains() method to search for a given value.

Let’s see the below program to understand it clearly.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>
/*
 *Creating a generic function to find an element inside the list
 */
template <typename T>
bool contains(std::list<T> &listOfElements, const T &element)
{
    // Find the iterator of element exists inside the list
    auto it = std::find(listOfElements.begin(), listOfElements.end(), element);
    //if iterator points to end return false
    return it != listOfElements.end();
}
int main()
{
    std::list<std::string> stringList =
        {"I", "am", "the", "yes", "hey", "from"};
    // Check for the element inside list
    bool res = contains(stringList, std::string("is"));
    std::cout << res << std::endl;
    res = contains(stringList, std::string("yes"));
    std::cout << res << std::endl;

    // List of ints
    std::list<int> numList =
        {10, 6, 89, 32, 3, 25};
    // Check if the number exists in list
    res = contains(numList, 3);
    std::cout << res << std::endl;
    res = contains(numList, 25);
    std::cout << res << std::endl;
}

Output :

0
1
1
1

Also Read: How to Access Element by Index in a Set