繁体   English   中英

func upper_bound的参数?

[英]The param of 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没有,为什么?

更改此:

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返回[first, last) upper_bound的迭代器i ,使得对于[first, i), comp(value, *j)每个迭代器j [first, i), comp(value, *j)false

现在, lower_bound提到:

lower_bound返回[first, last) lower_bound的迭代器i ,使得对于[first, i), comp(*j, value)每个迭代器j [first, i), comp(*j, value)true

因此,这两个函数都将使用您的operator < (如果您更仔细地检查标准,则在任何情况下都只会使用该运算符)。 那有什么变化呢?

参数的顺序!

问题在于tt &rconst ,在upper_bound的情况下,它的调用方式如下:

comp(value, *j)

在这里, *j将是您的const参数。

lower_bound的情况下,例如:

comp(*j, value)

在这里, value将是您的const参数。 这就是编译错误的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM