Open In App

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

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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,

  • begin and end are iterators that denotes the range of elements in the list container.
  • target is the specific element whose first occurrence is required.
  • it is an iterator pointing to the first occurrence of the specific element.

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++
// 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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads