![](/img/trans.png)
[英]How to to pass iterators to the std::lower_bound() comparison function?
[英]Comparison operator to be used in std::lower_bound
我的编译器拒绝编译以下简单代码:
struct mystruct{
int x;
bool operator<(const mystruct& y) const{ return x < y.x; }
};
std::map<mystruct, int> test;
auto it = std::lower_bound(test.begin(), test.end(), mystruct{2});
我遇到了错误
error C2893: Failed to specialize function template 'unknown-type std::less<void>::operator ()(_Ty1 &&,_Ty2 &&) const'
查看此链接,似乎您只需要定义一个常量比较运算符,这正是我在做的事情。 我在这里缺少什么吗?
问题在于映射的值类型为std::pair<const mystruct, int>
,因此std::lower_bound
试图将mystruct
与std::pair<const mystruct, int>
。 并且没有为此定义运算符。
无论如何,您都不应该在std::map
上使用std::lower_bound
。 因为映射没有随机访问迭代器,所以它将在O(n)中工作。 std::map
有其自己的lower_bound
成员函数,该函数将利用树结构为您提供O(log n)中的结果。
auto it = test.lower_bound(mystruct{2});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.