【问题标题】:Comparison operator to be used in std::lower_bound要在 std::lower_bound 中使用的比较运算符
【发布时间】:2015-05-28 03:47:14
【问题描述】:

我的编译器拒绝编译这个简单的代码:

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'

查看this 链接,您似乎只需要定义一个常量比较运算符,这正是我正在做的。我在这里有什么遗漏吗?

【问题讨论】:

    标签: c++ operator-overloading stl-algorithm


    【解决方案1】:

    问题在于您的地图的值类型是std::pair&lt;const mystruct, int&gt;,因此std::lower_bound 试图将mystructstd::pair&lt;const mystruct, int&gt; 进行比较。并且没有为此定义运算符。

    无论如何,您不应该在std::map 上使用std::lower_bound。它将在 O(n) 中工作,因为地图没有随机访问迭代器。 std::map 有自己的 lower_bound 成员函数,它将利用树形结构为您提供 O(log n) 的结果。

    auto it = test.lower_bound(mystruct{2});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 2017-08-30
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      相关资源
      最近更新 更多