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

前端 未结 10 1964
情深已故
情深已故 2021-01-31 08:40

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& whe         


        
10条回答
  •  独厮守ぢ
    2021-01-31 09:09

    If a vector has N elements, there are N+1 possible answers for find. std::find and std::find_if return an iterator to the found element OR end() if no element is found. To change the code as little as possible, your find function should return the equivalent position:

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

    I would still use std::find_if, though.

提交回复
热议问题