Open In App

How to Find All Occurrences of an Element in a List in C++?

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

In C++, std::list is a sequence container that allows non-contiguous memory allocation. As such, it is a doubly linked list that can be traversed in both directions. In this article, we will learn how to find all occurrences of a specific element in a list in C++.

Example:

Input:
myList = {7, 5, 16, 8, 5, 5, 8};
int Target = 5;

Output:
The element 5 occurred at indices: 1, 4, 5

Finding All Occurrences of an Element in a List in C++

In C++, std::list does not provide direct access to its elements by their position. Therefore, we cannot use indices to find all occurrences of elements. Instead, we iterate through the list compare each element with the target, and print the indices where the target integer is found.

C++ Program to Find All Occurrences of an Element in a List

The below example demonstrates how we can find all occurrences of a specific element in a std::list in C++.

C++
// C++ program to find all occurrences of a specific element
// in a list
#include <iostream>
#include <list>
using namespace std;

int main()
{
    list<int> myList = { 7, 5, 16, 8, 5, 5, 8 };
    int target = 5;
    bool found = false;

    cout << "Element " << target << " found at Position: ";

    // Iterate over the list elements
    int pos = 0;
    for (auto it = myList.begin(); it != myList.end();
         ++it, ++pos) {
        // If the current element matches the target
        if (*it == target) {
            cout << pos << " ";
            found = true;
        }
    }

    if (!found) {
        cout << "Not found";
    }

    return 0;
}

Output
Element 5 found at indices: 1 4 5 

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




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads