簡體   English   中英

對結構向量進行二進制搜索

[英]Binary search on the vector of structs

我有一個包含該結構的結構的結構向量

struct Main{

   int mainID;
   string mainDIV;
   string mainNAME;

}

有可能在結構上使用二進制搜索嗎? 我知道它易於使用

binary_search( vector.begin() , vector.end() , 5 )

但是有沒有一種方法可以通過回調或實際找到struct屬性的方法呢? 我找不到與該主題有關的任何內容。

是的,有可能。 valuestd::binary_search相比時容器中的元素需要才有意義。 在簡單的情況下(如果Main支持某個地方的operator< ),您將提供Main類型的元素作為值:

// check if this specific Main exists
bool yes = std::binary_search(v.begin(), v.end(), Main{0, "some", "strings"});

// does exactly the same thing as above
bool yes = std::binary_search(v.begin(), v.end(), Main{0, "some", "strings"}
    , std::less<Main>{});

如果它不支持operator< (或您的容器由其他東西排序,例如mainID ),那么您將必須自己提供一個比較器,該算法將使用:

// check if there is a Main with mainID 5
bool yes = std::binary_search(v.begin(), v.end(), 5,
    [](const Main& element, const int value) {
        return element.mainID < value;
    });

您必須向binary_search()提供信息,以告訴它如何比較對象。 兩種最常見的方法是,如果可能的話,將operator<()添加到struct ,或者提供可以比較兩個struct的輔助函數。

第一種形式如下所示:

struct Main {
  int mainID ;
  string mainDIV ;
  string mainNAME ;
  bool operator<(const Main & other) const
  {
    return mainID < other.mainID ;
  }
}

這只會在mainID上進行mainID ,但是您可以從那里進行擴展。

此外,這僅教編譯器如何比較兩個struct Main ,而上面@Barry的答案將匹配int和struct Main 但是,讓我們繼續這個答案。

現在要查找5的記錄,我們必須將其放入struct Main

struct Main search_key = { 5 } ;
bool yes = std::binary_search( v.begin(), v.end(), search_key ) ;

現在,這不是很優雅,此外,如果您具有struct Main的構造struct Main (並且未在示例中放置它),那么它甚至將無法工作。 因此,我們為int添加了另一個構造函數。

struct Main
{
    Main(int id, const string & a_div, const string & a_name ) : id(id), div(a_div), name(a_name) { }
    Main(int id) : id(id) { }
    int id ;
    string div, name ;

    bool operator<(const Main &o) const { return id < o.id ; }
} ;

現在我們可以做一個簡短的表格:

bool has_3 = std::binary_search( v.begin(), v.end(), Main( 3) ) ;

歷史記錄:Bjarne一直在嘗試將默認比較運算符納入標准,但並非所有人都對標准會議感到興奮。 我在上次會議上雖然取得了一些進展,所以最終可能在C ++ 17出現時才出現。

暫無
暫無

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

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