的std :: equal_range不具有运营商LT strucutre工作;定义运营商、定义、工作、std

2023-09-11 06:08:05 作者:你非柠檬怎知我心酸i

我想使用的std :: equal_range 的结构下面我有编译错误,指出错误:不对应的'运营商的LT;

I am trying to use std::equal_range with the structure below I have compilation error saying that 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);

我看着模板implementatino,什么是失败如下,其中 *它是deferenging的迭代器,指向MyFoo的对象和 VAL _ 10

I've looked into the template implementatino and what is failing is the following where *it is deferenging the iterator pointing to an object of MyFoo and val_ is 10.

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

为什么它不工作?我想可能是因为它正试图打电话给全球运营商的LT; 未被定义的,但因为我把它定义为类成员,它不应该是一个问题,是不是?

Why it is not working? I thought probably because it is trying to call the the global operator< that is not defined, but since I defined it as class member that should not be a problem, isn't it?

推荐答案

提供非会员比较符:

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

这可能是不必要的,因为编译器将能在其他地方你code执行无提示的转换。

Which is probably unwanted, since the compiler will be able to perform silent conversions in other places of your code.