簡體   English   中英

C ++ STL二進制搜索(lower_bound,upper_bound)

[英]C++ STL Binary Search (lower_bound, upper_bound)

我已經實現了這樣的二進制搜索:

typedef std::vector<Cell>::iterator CellVectorIterator;

typedef struct _Point {
    char x,y;
} CoordinatePoint;

typedef struct _Cell {
    ...
    CoordinatePoint coordinates;
} Cell;

struct CellEqualityByCoordinates
{
    bool
    operator()(const Cell& cell1, const Cell& cell2) const
    { return cell1.coordinates.x == cell2.coordinates.x && cell1.coordinates.y == cell2.coordinates.y; }
};

CellVectorIterator FindCellByCoordinates (CellVectorIterator first, CellVectorIterator last, const Cell &val)
{
    return std::upper_bound(first, last, val, CellEqualityByCoordinates());
}

但是,它並不總能找到價值。

怎么了

您的比較功能不適用於二進制搜索。 它不應該確定相等性,它應該確定順序關系。 具體來說,如果第一個參數在排序范圍內肯定要排在第二個參數之前,則應返回true。 如果參數應視為相等,或者第二個參數在第一個參數之前,則應返回false。 您的范圍也需要按照相同的條件進行排序,以便二進制搜索正常工作。

可能起作用的示例函數:

bool operator()(const Cell& cell1, const Cell& cell2) const 
{
    if (cell1.coordinates.x < cell2.coordinates.x) return true;
    if (cell2.coordinates.x < cell1.coordinates.x) return false;
    return cell1.coordinates.y < cell2.coordinates.y;
}

在短路布爾值評估中加倍作為教訓的類似示例將是:

bool operator()(const Cell& cell1, const Cell& cell2) const 
{
    return (cell1.coordinates.x < cell2.coordinates.x) ||
        (!(cell2.coordinates.x < cell1.coordinates.x) &&
          cell1.coordinates.y < cell2.coordinates.y);
}

兩者都具有稱為嚴格弱序的屬性。 在標准庫集合和搜索算法中經常需要進行各種排序和/或搜索。

另一個示例利用std::pair ,該對象已經具有適當的std::less重載,可以執行上述操作,因此使此操作復雜度大大降低:

bool operator()(const Cell& cell1, const Cell& cell2) const
{
    return std::make_pair(cell1.coordinates.x, cell1.coordinates.y) <
           std::make_pair(cell2.coordinates.x, cell2.coordinates.y);
}

可通過std::tie為元組提供類似的算法。

當然,所有這些都假定您首先具有一個實際的有序序列,並由相同的比較邏輯進行排序。 (我們只能假設它是真實的,因為沒有發布任何此類證據)。

暫無
暫無

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

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