Open In App

Find All Occurrences of an Element in a Vector

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to find all the occurrences of an element in a vector in C++.

The most effective method to find all occurrence of an element in a vector in C++ is by using find() function with a loop. Let’s take a look at an example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {2, 3, 2, 1, 5, 4, 2};
  	int val = 2;

    // Find the first occurrence of 2
    auto it = find(v.begin(), v.end(), val);

    // Check if the element was found
    while (it != v.end()) {
        cout << it - v.begin() << " ";

        // Search for the next occurrence of val
        it = find(it + 1, v.end(), val);
    }
    return 0;
}

Output
0 2 6 

Explanation: The above program finds all occurrences of a 2 in a vector using find(). It prints each index and updates the iterator to search for the next occurrence until the end of the vector is reached.

There are also some other methods in C++ by which we can find all occurrence of an element in a vector. Some of them are as follows:

Using find_if()

If we want more flexibility (e.g., finding elements based on a condition), find_if() function can be used with the desired condition.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {2, 3, 2, 1, 5, 4, 2};
    int val = 2;
    auto it = v.begin();

    // Find all occurrence of an element val
    while ((it = find_if(it, v.end(), [val](int n) { 
      return n == val; })) != v.end()) {
        cout << distance(v.begin(), it) << " ";
        ++it;
    }
    return 0;
}

Output
0 2 6 

Using Traditional Loop

Iterate through the vector and compare each value with the specified element. If a match is found at any index, print that index.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {2, 3, 2, 1, 5, 4, 2};
    int val = 2;

    // Find all occurrence of an element val
    for (int i = 0; i < v.size(); i++) {
        if (v[i] == val)
            cout << i << " ";
    }
    return 0;
}

Output
0 2 6 

Next Article
Article Tags :
Practice Tags :

Similar Reads