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

前端 未结 10 1872
情深已故
情深已故 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:48

    In this case, it is safe to cast away the unsigned portion unless your vector can get REALLY big.

    I would pull out the where.size() to a local variable since it won't change during the call. Something like this:

    int find( const vector& where, int searchParameter ){
        int size = static_cast(where.size());
        for( int i = 0; i < size; i++ ) {
           if( conditionMet( where[i], searchParameter ) ) {
               return i;
           }
        }
        return -1;
    }
    

提交回复
热议问题