2017-03-19 12 views
1

STL lower_bound関数に問題があります。私はC++を初めて使っています。私は、クラスビズのオブジェクトのベクトルをソートするために必要なので、私はこの種の使用:C++ lower_bound compare関数の問題

bool cmpID(const Biz & a, const Biz & b) { 
    return a.bizTaxID < b.bizTaxID; 
} 
sort(bussiness_list.begin(), bussiness_list.end(), cmpID); 

私はLOWER_BOUNDと別の関数にbizTaxIDによってオブジェクトビズを見つけるためにしようとすると問題があります。私はそのために同じ機能cmpIDを使うことができると思ったが、明らかではない:

taxID = itax; //function parameter, I am searching for the `Biz` with this ID 
auto it = lower_bound(bussiness_list.begin(), bussiness_list.end(), taxID, cmpID); 

私はコンパイルエラーを取得:「ブール値(定数ビズ&、constのビズ&を)」:「constのSTDから引数2を変換することはできません:: string 'to' const Biz & '

私は同じ検索機能を並べ替えと同様に使うことができると思いました。誰かが私に説明してくれるのですが、間違いはどこにありますか?lower_boundは私に渡す必要がありますか?私が言ったように、私はC++を初めて使っています。

ありがとうございます。

答えて

1

std::stringオブジェクト(itaxstd::stringであると仮定します)で検索する必要がある間に、比較関数にはBizオブジェクトが必要です。それはBizオブジェクトsearchObjにあなたのコンテナからBizオブジェクトを比較しようとすると

Biz searchObj; 
searchObj.bizTaxID = itax; 
auto it = lower_bound(bussiness_list.begin(), bussiness_list.end(), searchObj, cmpID); 

はその後、コンパイラはcmpIDを使用することができます。

最も簡単には、lower_boundコールのためにそのような何かをBizオブジェクトmeantsを作成することです。

また、あなたがstd::stringBizオブジェクトを比較する比較演算子を提供することができます:

inline bool cmpID(const Biz& biz, const std::string& str) 
{ 
    return biz.bizTaxID < str; 
} 

inline bool cmpID(const std::string& str, const Biz& biz) 
{ 
    return str < biz.bizTaxID; 
} 

また、私は、それから、あなたがC++の演算子ではなく、関数を定義することにcmpIDを渡す必要がお勧めしないだろうすべての関数(コンパイラは、使用する良い演算子を受け取る):

inline bool operator<(const Biz & a, const Biz & b) 
{ 
    return a.bizTaxID < b.bizTaxID; 
} 

inline bool operator<(const Biz& biz, const std::string& str) 
{ 
    return biz.bizTaxID < str; 
} 

inline bool operator<(const std::string& str, const Biz& biz) 
{ 
    return str < biz.bizTaxID; 
} 
+0

ありがとう!それは動作します。私は今それを理解していると思う。 –