C++ lower_bound 比较函数问题

C++ lower_bound compare function issue

我在使用 STL lower_bound 函数时遇到一些问题。我是 C++ 的新手。我需要对 class Biz 的对象向量进行排序,所以我使用了这种排序:

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

问题是当我试图在另一个函数 lower_bound 中通过 bizTaxID 找到对象 Biz 时。我以为我可以为此使用相同的函数 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);

我收到编译器错误:'bool (const Biz &,const Biz &)':无法将参数 2 从 'const std::string' 转换为 'const Biz &'

我想我可以对搜索和排序使用相同的比较功能。有人可以向我解释错误在哪里,lower_bound 到底需要我传递什么吗?正如我所说,我是 c++ 的新手。

提前致谢。

您的比较函数需要 Biz 个对象,而您需要搜索 std::string 个对象(假设 itaxstd::string)。

最简单的方法是为 lower_bound 调用创建一个 Biz 对象,类似于:

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

然后编译器可以使用 cmpID,因为它会尝试将容器中的 Biz 对象与 Biz 对象 searchObj 进行比较。

或者,您可以提供比较运算符来比较 Biz 对象与 std::string:

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; 
}