【问题标题】:std::equal_range not working with strucutre having operator< definedstd::equal_range 不适用于具有 operator< 定义的结构
【发布时间】:2014-06-19 14:24:59
【问题描述】:

我正在尝试将std::equal_range 与下面的结构一起使用我有编译错误说error: no match for ‘operator&lt;’

 struct MyFoo {
    int     v_;
    string  n_;
    bool operator<(int v) const
    { return v_ < v;}
 };

 vector<MyFoo> data; 
 // data is sorted by int v_
 typedef vector<MyFoo>::iterator Ptr;
 std::pair< Ptr, Ptr > pr = std::equal_range(data.begin(), data.end(), 10);

我已经查看了模板 implementationatino,失败的是以下*it 推迟指向 MyFoo 对象的迭代器,val_ 是 10。

 if(*it < val_) {
  ...
 }

为什么它不起作用?我想可能是因为它试图调用未定义的全局operator&lt; ,但由于我将它定义为不应该成为问题的类成员,不是吗?

【问题讨论】:

  • bool operator(int v) const - Umm
  • 错字..修复了帖子..错误真的是那个...
  • 当然someMyFoo &lt; someInt 可以,但someInt &lt; someMyFoo 不行。
  • ..所以最好在这两种情况下都有一个全局运算符...我很困惑,因为我只阅读了 lower_bound 的代码,而还有 upper_bound 需要相反的方式...
  • 要详细说明 chris 的评论:您需要一个 bool operator &lt; (int i, MyFoo &amp;f)

标签: c++ algorithm stl equal-range


【解决方案1】:

提供非成员比较运算符:

 bool operator<(int v, const MyFoo& foo)
 { 
   return foo.v_ < v;
 }

 bool operator<(const MyFoo& foo, int v)
 {
   return v < foo;
 }

或者,您可以为int 提供一个转换运算符:

operator int() cont {return v_;}

这可能是不需要的,因为编译器将能够在代码的其他位置执行静默转换。

【讨论】:

    【解决方案2】:

    作为另一种选择:提供

    bool operator<(const MyFoo& rhs) const { return v_ < rhs.v_; }
    

    并在虚拟对象上使用std::equal_range,正确的v_ 为:

    std::pair<Ptr, Ptr> pr = std::equal_range(data.begin(), data.end(), MyFoo{10, ""});
    

    【讨论】:

      【解决方案3】:

      您可能会遇到麻烦,因为 std::equal_range 实现使用 std::less。这将尝试将您的 MyFoo 转换为 int 进行比较,而不仅仅是使用 operator

      operator int() const
      {
          return v_;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-28
        • 2011-05-15
        • 2015-06-13
        • 2011-04-22
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多