I am trying to get the index of an element in a vector of strings, to use it as an index in another vector of int type, is this possible ?
Nobody mentioned the general version as a function for any std::vector so here it is (in one ugly line) :
#include
template long long int indexOf(const std::vector &vector , const T &data){
return (std::find(vector.begin(), vector.end(), data) != vector.end()) //Is it in the vector ?
?
std::distance(vector.begin(), std::find(vector.begin(), vector.end(), data)) //Yes, take the distance (C++11 and above, see the previous answers)
: -1; //No, return -1
}
And without the ternary operator :
#include
template long long int indexOf(const std::vector &vector , const T &data){
if((std::find(vector.begin(), vector.end(), data) != vector.end())){
return std::distance(vector.begin(), std::find(vector.begin(), vector.end(), data));
}
else{return -1;}
}
It returns either the index or -1 if the element is not in the vector.
Note that this may be very slow for big vectors, as it computes two times std::find.