代码之家  ›  专栏  ›  技术社区  ›  RED SOFT ADAIR

如何仅使用活页夹在地图中查找值

  •  3
  • RED SOFT ADAIR  · 技术社区  · 16 年前

    在地图的第二个值中搜索时,我使用如下内容:

    typedef std::map<int, int> CMyList;
    static CMyList myList;
    
    template<class t> struct second_equal
    {
        typename typedef t::mapped_type mapped_type;
        typename typedef t::value_type value_type;
    
        second_equal(mapped_type f) : v(f)   {};
        bool operator()(const value_type &a) { return a.second == v;};
    
        mapped_type v;
    };
    ...    
    int i = 7;
    CMyList::iterator it = std::find_if(myList.begin(), myList.end(), 
                                        second_equal<CMyList>(i));
    

    4 回复  |  直到 16 年前
        1
  •  8
  •   TimW    16 年前

    使用选择器从从映射中获取的值类型中选择第一个或第二个元素。 使用绑定器将值(i)绑定到 std::equal_to 使用编写器将选择器的输出用作equal_to函数的另一个参数。

    //stl version
    CMyList::iterator it = std::find_if(
        myList.begin(), 
        myList.end(), 
        std::compose1(
            std::bind2nd(equal_to<CMyList::mapped_type>(), i), 
            std::select2nd<CMyList::value_type>())) ;
    
    //Boost.Lambda or Boost.Bind version
    CMyList::iterator it = std::find_if(
        myList.begin(), 
        myList.end(), 
        bind( &CMyList::mapped_type::second, _1)==i);
    
        2
  •  0
  •   Matthieu M.    16 年前

    _.second 现在。

    因此,我个人使用:

    template <class Second>
    class CompareSecond
    {
    public:
      CompareSecond(Second const& t) : m_ref(t) {} // actual impl use Boost.callparams
      template <class First>
      bool operator()(std::pair<First,Second> const& p) const { return p.second == m_ref; }
    private:
      Second const& m_ref;
    };
    

    我将其与:

    template <class Second>
    CompareSecond<Second> compare_second(Second const& t)
    {
      return CompareSecond<Second>(t);
    }
    

    这样我就可以写了

    CMyList::iterator it = std::find_if(myList.begin(), myList.end(), compare_second(i));
    

    没错,它不使用活页夹。

    :

     CMyList::iterator it = toolbox::find_if(myList, compare_second(i));
    

    哪一个(imho)清晰易读,无需 auto 用于类型推断的关键字。

        3
  •  0
  •   user184968 user184968    16 年前

    你可以用 Boost Lambda

    CMyList::iterator it = std::find_if(
          myList.begin(), myList.end(), 
          boost::lambda::bind(&CMyList::value_type::second, boost::lambda::_1) == i);
    
        4
  •  -1
  •   Community Mohan Dere    9 年前

    template <typename Iter, typename T>
    Iter find_second(Iter first, Iter last, T value) {
        while (first != last) {
            if (first->second == value) {
                return first;
            }
            ++first;
        }
        return first;
    }
    

    这没有经过测试,甚至没有经过编译。

    Matthieu M. 想出。