我在使用 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/