【问题标题】:Using std::any_of with lambda calling overloaded equality operator使用带有 lambda 调用重载相等运算符的 std::any_of
【发布时间】:2015-09-24 05:12:33
【问题描述】:

我有以下课程:

Class Foo {
public:
    bool operator ==(const Foo& f);
    ...
private:
    set<pair<int,int>> points;
    ...
}

如果两个 Foo 对象具有相等的点集,则重载的相等运算符返回 true。如果我这样使用它,它会按预期工作:

Foo a = Foo();
Foo b = Foo();
if (a == b) ...

我的问题是,为什么以下编译失败?

vector<Foo> foos = ...
Foo c = ...
if (any_of(foos.begin(),foos.end(),[c](const Foo& f) { return (f == c); }))
{
    // stuff
} 

【问题讨论】:

  • 你应该发布编译错误。

标签: c++ lambda stl-algorithm


【解决方案1】:

在您的 lambda 中,fconst。所以你不能打电话给你的operator==,因为你的operator==不是const。所以修复它:

bool operator==(const Foo& f) const;

【讨论】:

    猜你喜欢
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    相关资源
    最近更新 更多