首页 > 解决方案 > 如何将 std::find 用于类向量?

问题描述

class g {
public:
    int x, y, z;
};
vector<g>f;
int main() {
    g obj1 = { 1,2,3 };
    f.push_back(obj1);
    auto it = find(f.begin(), f.end(), 2);
    f.erase(it);
}

这段代码给了我一个 C2678 错误:二进制 '==': no operator found 它采用 'g' 类型的左操作数。

标签: c++vector

解决方案


您应该==为您的类实现运算符:

class g {
public:
    int x, y, z;

    bool operator==(const g& o) const {
        return x == o.x && y == o.y && z == o.z;
    }
};

使用正确的类型作为参数:

auto it = std::find(f.begin(), f.end(), g{1, 2, 3});

推荐阅读