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

前端 未结 10 1876
情深已故
情深已故 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 08:44

    std::vector has random-access iterators. You can do pointer arithmetic with them. In particular, this my_vec.begin() + my_vec.size() == my_vec.end() always holds. So you could do

    const vector::const_iterator pos = std::find_if( firstVector.begin()
                                                         , firstVector.end()
                                                         , some_predicate(parameter) );
    if( position != firstVector.end() ) {
        const vector::size_type idx = pos-firstVector.begin();
        doAction( secondVector[idx] );
    }
    

    As an alternative, there's always std::numeric_limits::size_type>::max() to be used as an invalid value.

提交回复
热议问题