簡體   English   中英

upper_bound和lower_bound值要求不一致

[英]upper_bound and lower_bound inconsistent value requirements

我看到在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;
}

我不認為這是一個錯誤。 如果您查看std::upper_bound(可能)實現 ,則比較完成如下

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

並且由於operator<MyInt的成員函數(而不是不是int的成員函數, int不是類類型),因此代碼不會編譯,因為沒有從MyIntint轉換。 另一方面,在std::lower_bound*it出現在比較的lhs上,並且value (類型為int )在傳遞給MyInt::operator<時可以隱式轉換為MyInt

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

這就是為什么將比較運算符實現為非成員更好的原因,因此您就不會有這種不對稱性。 Scott Meyers的有效C ++書中也提到了這一點: 項目24:當類型轉換應應用於所有參數時,聲明非成員函數

快速而骯臟的修復:定義MyInt::operator int(){return val;}以將MyInt隱式轉換為int 編輯:並不真正起作用,含糊不清)。 有效的方法是消除對隱式轉換的需求

set<MyInt>::iterator itU = upper_bound(s.begin(), s.end(), MyInt(2));

代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM