[英]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 &r
是const
,在upper_bound
的情況下,它的調用方式如下:
comp(value, *j)
在這里, *j
將是您的const參數。
在lower_bound
的情況下,例如:
comp(*j, value)
在這里, value
將是您的const參數。 這就是編譯錯誤的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.