2017-10-09 86 views
1

代码:func upper_bound的参数?

#include "inc.h" 
#include <string> 
#include <vector> 
#include <algorithm> 
#include <iostream> 
using namespace std; 


class tt{ 
    public: 
     tt(int i): i(i) {} 
     int i; 
     bool operator < (const tt &r) 
     { 
      return i < r.i; 
     } 

}; 



int test_lower_bound() 
{ 
    vector<tt> a; 
    a.push_back(tt(1)); 
    a.push_back(tt(2)); 
    a.push_back(tt(3)); 
    a.push_back(tt(4)); 
    a.push_back(tt(5)); 

    vector<tt>::iterator result = lower_bound(a.begin(), a.end(), tt(3)); 
    cout << result->i << endl; 
    return 0; 
} 

int test_upper_bound() 
{ 
    vector<tt> a; 
    a.push_back(tt(1)); 
    a.push_back(tt(2)); 
    a.push_back(tt(3)); 
    a.push_back(tt(4)); 
    a.push_back(tt(5)); 

    vector<tt>::iterator result = upper_bound(a.begin(), a.end(), tt(3)); 
    cout << result->i << endl; 
    return 0; 
} 

int main(int argc, char** argv) 
{ 
    test_lower_bound(); 
    return 0; 
} 

在编译时,它会产生这样的错误:

In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/algorithm:62, 
       from main.cc:4: 
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_algo.h: In function ‘_FIter std::upper_bound(_FIter, _FIter, const _Tp&) [with _FIter = __gnu_cxx::__normal_iterator<tt*, std::vector<tt, std::allocator<tt> > >, _Tp = tt]’: 
main.cc:45: instantiated from here 
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_algo.h:2542: error: passing ‘const tt’ as ‘this’ argument of ‘bool tt::operator<(const tt&)’ discards qualifiers 

从结果中我们可以看到,upper_bound有一个错误,但lower_bound没有,为什么?

回答

0

更改此:

bool operator < (const tt &r) { return i < r.i; } 

这样:

bool operator < (const tt &r) const { return i < r.i; } 

,因为你需要标记您的运营商如const,为了能够在const操作运行。


“为什么错误显示为upper_bound而不是lower_bound?”

如果选中的upper_bound标准,它说:

upper_bound returns the furthermost iterator i in [first, last) such that, for every iterator j in [first, i), comp(value, *j) is false .

现在,lower_bound,另一方面提到:

lower_bound returns the furthermost iterator i in [first, last) such that, for every iterator j in [first, i), comp(*j, value) is true .

所以这两种功能会使用你的operator <(如果你检查标准更密切,他们只会在任何情况下使用该运营商)。那么有什么变化?

参数的顺序!

问题是tt &rconst,并在upper_bound的情况下,这就是所谓的喜欢:

comp(value, *j) 

这里,*j将是你的const的说法。

虽然lower_bound的情况下,如:

comp(*j, value) 

这里,value将是你的const的说法。这是编译错误的原因。

+1

我不认为这实际上是依赖于实现的。标准指定'lower_bound'返回一个迭代器'i',其中'* j <值'为''之前的每个'j','upper_bound'返回一个迭代器'i',其中'!(值< * j)在'i'之前的每个'j','value'是'const T&'。所以'operator <'参数的顺序和常量被精确指定。 – aschepler

+0

与大多数标准算法一样,'lower_bound'将永远不会使用'operator'',只有'operator <'。 – aschepler

+0

@aschepler非常感谢你,回复更新! – gsamaras