To get the index of a specified item in a vector in C++, you can use algorithms like std::find
or std::find_if
.
In this example,
vec
containing numeric elements.std::find
algorithm from the algorithm
header to search for the specified item.std::find
returns an iterator pointing to the found element. We calculate the index by subtracting the beginning iterator from the found iterator.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int item = 3;
auto it = std::find(vec.begin(), vec.end(), item);
if (it != vec.end()) {
int index = std::distance(vec.begin(), it);
std::cout << index << std::endl;
}
return 0;
}
2
In this example,
vec
containing string elements.std::find
algorithm from the algorithm
header to search for the specified item.std::find
returns an iterator pointing to the found element. We calculate the index by subtracting the beginning iterator from the found iterator.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> vec = {"apple", "banana", "cherry", "date"};
std::string item = "banana";
auto it = std::find(vec.begin(), vec.end(), item);
if (it != vec.end()) {
int index = std::distance(vec.begin(), it);
std::cout << index << std::endl;
}
return 0;
}
1
In this tutorial, we learned How to get the Index of Specified Item in a Vector in C++ language with well detailed examples.