![]() |
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 VectorThe 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 VectorC++
Output
The element 2 occurred at indices: 0, 2, 6, Time Complexity: O(N), because std::find() implements linear search. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |