sharptooth - 1 year ago 100

C++ Question

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()`

`size_t`

`unsigned int`

`-1`

`size_t`

`int`

Answer Source

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.