Find index of an element in vector in C++
This post will discuss how to find the index of the first occurrence of a given element in vector in C++.
1. Using std::find
with std::distance
function
The simplest solution is to use the std::find
algorithm defined in the <algorithm>
header. The idea is to get the index using std::distance
on the iterator returned by std::find
, which points to the found value. We can also apply pointer arithmetic to the iterators. Therefore, the -
operator would also work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = { 7, 3, 6, 2, 6 }; int key = 6; std::vector<int>::iterator itr = std::find(v.begin(), v.end(), key); if (itr != v.cend()) { std::cout << "Element present at index " << std::distance(v.begin(), itr); } else { std::cout << "Element not found"; } return 0; } |
Output:
Element present at index 2
2. Using std::find_if
with std::distance
function
We can also use the standard algorithm std::find_if
, which accepts a predicate. This is the recommended approach if the search needs to satisfy certain conditions. For example, finding the index of the first string starting with some character in a vector of strings.
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> struct compare { int key; compare(int const &i): key(i) {} bool operator()(int const &i) { return (i == key); } }; int main() { std::vector<int> v = { 7, 3, 6, 2, 6 }; int key = 6; auto itr = std::find_if(v.cbegin(), v.cend(), compare(key)); if (itr != v.cend()) { std::cout << "Element present at index " << std::distance(v.cbegin(), itr); } else { std::cout << "Element not found"; } return 0; } |
Output:
Element present at index 2
3. Naive Solution
Finally, we can write our own routine for this, as demonstrated below:
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 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = { 7, 3, 6, 2, 6 }; int key = 6; bool found = false; for (int i = 0; i < v.size(); i++) { if (v[i] == key) { std::cout << "Element present at index " << i; found = true; break; } } if (!found) { std::cout << "Element not found"; } return 0; } |
Output:
Element present at index 2
That’s all about finding the index 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 :)