Original Post
How do I get the index value of the iterator returned by std::find?
-CProgrammer
std::distance(first, last); const int size = 50;
double array[size];
//... populate array with values
bool isLessThanSeven(double d) {
return d < 7;
}
//array is a double* and that is the iterator type returned
double* pos = std::find(array, array+size, isLessThanSeven);
int index = std::distance(array, pos);
template<typename FwdIt, typename Elem>
size_t index(FwdIt first, FwdIt last, Elem value)
{
size_t index = 0;
for( ;first != last; ++first, ++index )
if(*first == value) return index;
return static_cast<size_t>(-1); // for the purists, that's how GNU
// libstdc++ defines std::string::npos
}
template<typename FwdIt, typename UnaryPred>
size_t index_if(FwdIt first, FwdIt last, UnaryPred pred)
{
size_t index = 0;
for( ;first != last; ++first, ++index )
if(pred(*first)) return index;
return static_cast<size_t>(-1); // for the purists, that's how GNU
// libstdc++ defines std::string::npos
}
quote:
Original post by petewood
std::find takes and return iterators
const int size = 50;
double array[size];
//... populate array with values
bool isLessThanSeven(double d) {
return d < 7;
}
//array is a double* and that is the iterator type returned
double* pos = std::find(array, array+size, isLessThanSeven);
int index = std::distance(pos, array);
quote:
Original post by CProgrammer
Im not too familiar with STL, so std::find basically returns a pointer to the array value found. Thanks.
quote:
Original post by CProgrammer
petewood: Its std::distance(array, pos);
But it works great now thanks everybody.
This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more