O.Č*_*rič 2 c++ stl binary-search
我在使用 STL 下限函数时遇到了一些问题。我是 C++ 的新手。我需要对 Biz 类的对象向量进行排序,所以我使用了这种排序:
bool cmpID(const Biz & a, const Biz & b) {
return a.bizTaxID < b.bizTaxID;
}
sort(bussiness_list.begin(), bussiness_list.end(), cmpID);
Run Code Online (Sandbox Code Playgroud)
问题是当我尝试bizTaxID在另一个具有 lower_bound 的函数中找到一个对象 Biz by时。我以为我可以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);
Run Code Online (Sandbox Code Playgroud)
我收到编译器错误:'bool (const Biz &,const Biz &)': 无法将参数 2 从 'const std::string' 转换为 'const Biz &'
我想我可以使用相同的比较功能进行搜索和排序。有人可以向我解释错误在哪里,究竟lower_bound需要我传递什么?正如我所说,我是 C++ 的新手。
先感谢您。
您的比较函数需要Biz对象,而您需要对std::string对象进行搜索(假设itax是 a std::string)。
最简单的方法是创建一个Biz用于lower_bound调用的对象,如下所示:
Biz searchObj;
searchObj.bizTaxID = itax;
auto it = lower_bound(bussiness_list.begin(), bussiness_list.end(), searchObj, cmpID);
Run Code Online (Sandbox Code Playgroud)
然后编译器可以使用,cmpID因为它会尝试将Biz容器中的Biz对象与object进行比较searchObj。
或者,您可以提供比较运算符来将Biz对象与 a进行比较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;
}
Run Code Online (Sandbox Code Playgroud)
另外,我建议您定义 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;
}
Run Code Online (Sandbox Code Playgroud)