Find All Occurrences of an Element in a Vector
Last Updated :
06 Feb, 2024
In C++, std::vector is a dynamic array that stores elements in a similar way to C-style arrays, but it is automatically resizable and provides some built-in functions for different operations. In this article, we will learn how to find the indexes of all occurrences of an element within a vector in C++.
For example,
Input:
myVector = {2,3,2,1,5,4,2};
element = 2
Output:
The element 2 occurred at indices : 0, 2, 6
Find All Occurrences of an Element in a Vector
The C++ STL provides the std::find() function, which returns the first occurrence of a given element in a container. We can use this function with vectors and keep searching for the given element repeatedly till the end to find all the occurrences.
C++ Program To Find All Occurrences of an Element in Vector
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > arr = { 2, 3, 2, 1, 5, 4, 2 };
int element = 2;
auto it = find(arr.begin(), arr.end(), element);
cout << "The element " << element
<< " occurred at indices: " ;
while (it != arr.end()) {
cout << it - arr.begin() << ", " ;
it = find(it + 1, arr.end(), element);
}
cout << endl;
return 0;
}
|
Output
The element 2 occurred at indices: 0, 2, 6,
Time Complexity: O(N), because std::find() implements linear search.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...