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++ Program to Find All Occurrences of an Element in a // Vector #include <algorithm> #include <iostream> #include <vector> using namespace std;
int main()
{ // Initialize a vector array
vector< int > arr = { 2, 3, 2, 1, 5, 4, 2 };
// Element to search
int element = 2;
// Find the first occurrence of the element in the
// vector
auto it = find(arr.begin(), arr.end(), element);
// Check if the element was found
cout << "The element " << element
<< " occurred at indices: " ;
while (it != arr.end()) {
// Print the index of the element
cout << it - arr.begin() << ", " ;
// Search for the next occurrence and keeping
// beggining of the range after the currenly found
// occurence to avoid infinite loop
it = find(it + 1, arr.end(), element);
}
cout << endl;
return 0;
} |
The element 2 occurred at indices: 0, 2, 6,
Time Complexity: O(N), because std::find() implements linear search.
Auxiliary Space: O(1)