Find indices of all occurrences of an element in a vector in C++
This post will discuss how to find the indices of all occurrences of an element in a vector in C++.
1. Using std::find_if
To find the indices of all occurrences of an element in a vector, we can repeatedly call the std::find_if function within a loop. The following example efficiently calls the std::find_if function, where the search for the next element begins at the previous match.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> #include <vector> #include <algorithm> template<typename T> std::vector<int> findItems(std::vector<T> const &v, int target) { std::vector<int> indices; auto it = v.begin(); while ((it = std::find_if(it, v.end(), [&] (T const &e) { return e == target; })) != v.end()) { indices.push_back(std::distance(v.begin(), it)); it++; } return indices; } int main() { std::vector<int> v = {2, 1, 3, 6, 6, 7, 6, 8}; int target = 6; std::vector<int> indices = findItems(v, target); for (auto &e: indices) { std::cout << e << ' '; } return 0; } |
Output:
3 4 6
2. Using Loop
The idea here is to perform a linear scan of the vector and report indices of all matching elements with the target. This is demonstrated below using iterators. Note that to get the required index, std::distance is used (or apply pointer arithmetic).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> #include <vector> #include <algorithm> #include <iterator> template<typename T> std::vector<int> findItems(std::vector<T> const &v, int target) { std::vector<int> indices; for (auto it = v.begin(); it != v.end(); it++) { if (*it == target) { indices.push_back(std::distance(v.begin(), it)); } } return indices; } int main() { std::vector<int> vec = {2, 1, 3, 6, 6, 7, 6, 8}; int target = 6; std::vector<int> indices = findItems(vec, target); for (auto &e: indices) { std::cout << e << ' '; } return 0; } |
Output:
3 4 6
We can simplify the above code with a regular for-loop:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> #include <vector> #include <algorithm> template<typename T> std::vector<int> findItems(std::vector<T> const &v, int target) { std::vector<int> indices; for (int i = 0; i < v.size(); i++) { if (v[i] == target) { indices.push_back(i); } } return indices; } int main() { std::vector<int> vec = {2, 1, 3, 6, 6, 7, 6, 8}; int target = 6; std::vector<int> indices = findItems(vec, target); for (auto &e: indices) { std::cout << e << ' '; } return 0; } |
Output:
3 4 6
That’s all about finding the indices of all occurrences of an element in a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)