c++ - func upper_bound 的参数?

标签 c++ function debugging gcc constants

代码:

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

因为您需要将您的运算符(operator)标记为 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 论点。这就是编译错误的原因。

关于c++ - func upper_bound 的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46645246/

相关文章:

c++ - 类函数的 undefined reference 错误

c++ - 字符串下标超出范围 - 字符串冒泡排序

c++ - 理解 C++ 共享指针

javascript - 在 jQuery 插件中接受文本字符串而不是元素

python - 修改 `**kwargs` 字典总是安全的吗?

asp.net - 编译调试 ="false"和 Release模式有什么区别?

c++ - 进入带有并行for循环的编译指示(C++,OpenMP,Nsight Eclipse IDE)

c++ - 2010 年 3 月的最佳 Eclipse CDT (C++) 体验

matlab - 从返回结构体的函数返回一个字段

c# - 如何在 C# 程序中放置 "IF DEBUG"条件?