【问题标题】:C++ lower_bound compare function issueC++ 下界比较函数问题
【发布时间】:2017-03-19 09:16:37
【问题描述】:

我在使用 STL 下限函数时遇到了一些问题。我是 C++ 新手。我需要对 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 &)': cannot convert argument 2 from 'const std::string' to 'const Biz &'

我认为我可以使用相同的比较函数进行搜索和排序。有人可以向我解释错误在哪里,lower_bound 究竟需要我传递什么?正如我所说,我是 C++ 新手。

提前谢谢你。

【问题讨论】:

    标签: c++ stl binary-search


    【解决方案1】:

    您的比较函数采用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; 
    }
    

    【讨论】:

    • @jpo38 重载运算符的方法是否不需要支持 C++14 特性“异构关联查找”(N3657)
    • @marcbf:我认为 C++11 已经足够了。
    • @jpo38 嗯......我无法让它与 MSVC 2013 一起工作(是的,我们仍然在这里......暂时)。我得到与 OP 相同的错误。目前,我正在使用那个 hack,其中我使用带有虚拟变量的 lambda 作为第二个参数。不过,我确实更喜欢你的方法,如果我能用它就好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多