How to get position of a certain element in strings vector, to use it as an index in ints vector?

后端 未结 4 2027
我寻月下人不归
我寻月下人不归 2020-12-07 13:47

I am trying to get the index of an element in a vector of strings, to use it as an index in another vector of int type, is this possible ?

4条回答
  •  半阙折子戏
    2020-12-07 14:20

    Nobody mentioned the general version as a function for any std::vector so here it is (in one ugly line) :

    #include 
    
    template  long long int indexOf(const std::vector &vector , const T &data){
    
       return (std::find(vector.begin(), vector.end(), data) != vector.end()) //Is it in the vector ?
               ?
               std::distance(vector.begin(), std::find(vector.begin(), vector.end(), data)) //Yes, take the distance (C++11 and above, see the previous answers)
               : -1; //No, return -1
    }
    

    And without the ternary operator :

    #include 
    
    template  long long int indexOf(const std::vector &vector , const T &data){
    
         if((std::find(vector.begin(), vector.end(), data) != vector.end())){
             return std::distance(vector.begin(), std::find(vector.begin(), vector.end(), data));
         }
         else{return -1;}
    }
    

    It returns either the index or -1 if the element is not in the vector.


    Note that this may be very slow for big vectors, as it computes two times std::find.

提交回复
热议问题