c++ - std::equal_range 不适用于具有 operator< 定义的结构

标签 c++ algorithm stl equal-range

我正在尝试使用 std::equal_range使用下面的结构我有编译错误说 error: no match for ‘operator<’ .

 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);

我查看了模板实现,失败的是以下位置 *it正在取消指向 MyFoo 和 val_ 对象的迭代器是 10。

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

为什么它不起作用?我想可能是因为它试图调用全局 operator< 那没有定义,但既然我将它定义为类成员,那应该不是问题,不是吗?

最佳答案

提供非成员比较运算符:

 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_;}

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

关于c++ - std::equal_range 不适用于具有 operator< 定义的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24308993/

相关文章:

c++ - Boost 线程示例显示错误,它无法匹配调用 'boost::thread::thread(<unresolved overloaded function type>)' 的函数

c++ - g_hash_table 和 OpenMp

c++ - 交换两个数组而不完全分配第三个数组 (C++)

algorithm - 在附加条件下查找数组中可能的序列数

algorithm - 以数值方式求解具有二元变量的多元非线性方程组的最快方法是什么?

c - 如何删除带有随机指针的链表?

c++ - "end()"后插入器的迭代器?

c++ - 没有预定义的构造函数存在 C++

c++ - 作为程序员进行开发

c++ - c++/mfc/STL 中两个数组的差异函数?