我正试图在upper_bound
上使用vector<pair<int,int>>
,如下所示:
vector<pair<int,int>> data;
auto up = upper_bound(data.begin(), data.end(), 0);
VS2012给出了以下错误:
error C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'const int'
为什么要尝试将const int
与pair<int,int>
进行比较?
我尝试编写自己的比较函数,但它没有改变任何东西。如果我这样做,编译器会尝试将pair<int,int>
转换为const int
。
答案 0 :(得分:5)
您正在将一对与数字进行比较,因此没有预定义的比较运算符。您可能希望将其更改为以下内容:
auto up = upper_bound(data.begin(), data.end(), make_pair(0, 0));
或者,如果您的应用程序中有一个特定逻辑用于比较一对数字,您可以提供自己的比较功能:
bool cmp(int n, pair<int, int> const& p)
{
// For instance...
return ((p.first < n) && (p.second < n));
}
int main()
{
vector<pair<int,int>> data;
auto up = upper_bound(data.begin(), data.end(), 0, cmp);
}
答案 1 :(得分:2)
为什么要尝试将const int与一对比较?
因为你说过了。您的比较值为0
,但您的元素类型为pair<int,int>
。
Duh doy!
也许您正在寻找:
auto up = upper_bound(data.begin(), data.end(), make_pair(0, 0));
答案 2 :(得分:0)
std::upper_bound
的第三个参数是返回的迭代器指向的元素应该大于的值。您如何确定std::pair<int,int>
是否大于0
?
你传递的内容几乎肯定是std::pair<int,int>
:
auto up = upper_bound(data.begin(), data.end(), std::make_pair(first, second));
但是,first
和second
取决于您尝试解决的问题。
答案 3 :(得分:0)
如果您要搜索不兼容的类型,则需要特别注意比较功能。引自cppreference.com:
比较函数的签名应等同于以下内容:
bool cmp(const Type1 &a, const Type2 &b);
[...]类型
Type1
必须使T
类型的对象可以隐式转换为Type1
。类型Type2
必须是ForwardIt
类型的对象可以取消引用,然后隐式转换为Type2
。
- 在您的情况下,Type1
= int
和Type2
= std::pair<int, int>
。这应该可以解决问题。