std::map find_if condition style confusion

前端 未结 8 1152
星月不相逢
星月不相逢 2021-02-01 23:43

I\'d like to use std::find_if to search for the first element in my map that has a certain value in a specific element of its value structure. I\'m a little confus

8条回答
  •  生来不讨喜
    2021-02-02 00:12

    Elements in the map are not sorted by value, they are sorted according to the key. So the phrase "the first element" has not much sense.

    To find some element (not the first) that has x equal to some value you can write the functor as follows:

    struct check_x
    {
      check_x( int x ) : x_(x) {}
      bool operator()( const std::pair& v ) const 
      { 
        return v.second.x == x_; 
      }
    private:
      int x_;
    };
    

    Then use it as follows:

    // find any element where x equal to 10
    std::find_if( myMap.begin(), myMap.end(), check_x(10) );
    

提交回复
热议问题