Open In App

How to Find First Occurrence of an Element in a List in C++?

In C++, the list is a sequence container that stores data in non-contiguous memory allocation. It is defined in the STL (Standard Template Library) inside the <list> header. In this article, we will learn how to find the first occurrence of a specific element in a list in C++.

Example:

Input:
myList = {81, 22, 42, 33, 42, 23}
Target = 42

Output: 
First occurrence of element 42 is found at index : 2

Find the First Occurrence of an Element in a List in C++

To find the first occurrence of a specific element in a std::list in C++, we can use the std::find() function that is part of the <algorithm> header of C++. It returns an iterator that points to the first occurrence of the target element if it is present in the list. Otherwise, it returns the iterator pointing to the end of the list.

Syntax of std::find in C++

auto it = find(list.begin(),list.end(),target);

Here,

C++ Program to Find the First Occurrence of an Element in a List

The below example demonstrates how to find the first occurrence of a specific element in a given list in C++.

// C++ program to demonstrate how to find the first
// occurrence of a specific element in a given list

#include <algorithm>
#include <iostream>
#include <list>
using namespace std;

int main()
{
    // Initializing a list of integers
    list<int> myList = { 81, 22, 42, 33, 42, 23 };

    // Declare the element whose first occurrence is to be
    // found
    int element = 42;

    // Finding the first occurrence of the element
    auto it = find(myList.begin(), myList.end(), element);

    // Printing the position of the first occurrence of the
    // element
    if (it != myList.end()) {
        // calculating the index of the first occurrence of
        // the elment
        int position = distance(myList.begin(), it);
        cout << "First occurrence of element " << element
             << " is found at  index : " << position
             << endl;
    }
    else {
        cout << "Element not found in the list" << endl;
    }

    return 0;
}

Output
First occurrence of element 42 is found at  index : 2

Time Complexity: O(N), where N is the number of elements in the list.
Auxiliary Space: O(1)

Article Tags :