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 integral 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?
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. Ifstd::vectorhas size equal tostd::numeric_limits<size_t>::max(), then maximum allowed index will be(std::numeric_limits<size_t>::max()-1), since elements counted from 0.