C++ lower_bound 比较函数问题

标签 c++ stl binary-search

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

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 对象(假设 itax 是一个 std::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; 
}

关于C++ lower_bound 比较函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42884862/

相关文章:

c++ - 如果没有找到 map 元素会返回什么?

c++ - 在 C++ 中,我可以从 std::variant 中移出一些东西吗?

查找一组 git 项目何时损坏的算法?

c# - 二进制搜索字符串数组未找到搜索的字符串 C#

c++ - 返回 CArray 的问题

C++ STL 比较类 : how to parameterize comp-class behaviour?

c++ - 我如何使用 C/C++ 获得对特定内存地址的 R/W 访问权限

java - 使用比较器进行二分搜索

c++ - 非递归 Kosaraju 的两遍算法实现永远在大型数据集上执行

c++ - sqrt(int_value + 0.0) -- 它有目的吗?