sharptooth sharptooth - 1 year ago 145
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] );

which corresponds to an
unsigned int
type that can't directly store
. How do I signal that the element is not found in a vector when using
instead of
as an index?

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download