upper_bound和lower_bound不一致的值要求

aho*_*aho 5 c++ stl lower-bound implicit-conversion upperbound

我看到了std :: lower_bound()和std :: upper_bound()语法中的不一致(好吧,类型转换,真的),并且想知道是否有人可以解释一下吗?根据评论,第2行尽管与第1行明显相似,但不会编译; 你需要使用第3行显示的表格(至少在gcc 4.7.3/ubuntu 64位上 - 这就是我必须要玩的)

#include <set>
#include <algorithm>

using namespace std;

class MyInt {
  private:
    int val;
  public:
    MyInt(int _val): val(_val) {}
    bool operator<(const MyInt& other) const {return val < other.val;}
};

int main() {
    set<MyInt> s;
    s.insert(1);  // demonstrate implicit conversion works
    s.insert(MyInt(2));
    s.insert(3); // one last one for the road
    set<MyInt>::iterator itL = lower_bound(s.begin(), s.end(), 2); //LINE 1
    // the line below will NOT compile
    set<MyInt>::iterator itU = upper_bound(s.begin(), s.end(), 2); //LINE 2
    // the line below WILL compile
    set<MyInt>::iterator itU2 = upper_bound(s.begin(), s.end(), MyInt(2)); // LINE 3
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

vso*_*tco 5

我不认为这是一个错误.如果你看一下(可能的)实现std::upper_bound,比较就像是

if (!(value < *it)) { ... } // upper_bound, implicit conversion `MyInt`->`int` doesn't work
Run Code Online (Sandbox Code Playgroud)

并且因为operator<MyInt(而不是int类型)的成员函数,代码不能编译,因为没有转换MyIntint.另一方面,in std::lower_bound,*it出现在比较的lhs上,并且value(类型int)可以MyInt在传递给时隐式转换为MyInt::operator<.

if (*it < value) { ... } // lower_bound, implicit conversion `int`->`MyInt` works
Run Code Online (Sandbox Code Playgroud)

这就是为什么将比较运算符作为非成员实现更好的原因,因此您没有这种不对称性.Scott Meyers的Effective C++书中也提到了这一点:第24项:当类型转换应该适用于所有参数时,声明非成员函数.

快速和脏修复:定义MyInt::operator int(){return val;}隐式转换MyIntint.(编辑:不起作用,模棱两可).有效的是消除了隐式转换的需要

set<MyInt>::iterator itU = upper_bound(s.begin(), s.end(), MyInt(2));
Run Code Online (Sandbox Code Playgroud)

代替.