sharptooth sharptooth - 2 months ago 19
C++ Question

How do I find an element position in std::vector?

I need to find an element position in an std::vector to use it for referencing an element in another vector:

int find( const vector<type>& where, int searchParameter )
{
for( int i = 0; i < where.size(); i++ ) {
if( conditionMet( where[i], searchParameter ) ) {
return i;
}
}
return -1;
}
// caller:
const int position = find( firstVector, parameter );
if( position != -1 ) {
doAction( secondVector[position] );
}


however
vector::size()
returns
size_t
which corresponds to an
unsigned int
type that can't directly store
-1
. How do I signal that the element is not found in a vector when using
size_t
instead of
int
as an index?

Answer

You could use std::numeric_limits<size_t>::max() for elements that was not found. It is a valid value, but it is impossible to create container with such max index. If std::vector has size equal to std::numeric_limits<size_t>::max(), then maximum allowed index will be (std::numeric_limits<size_t>::max()-1), since elements counted from 0.