c++ - 如何使用 std::find 作为类 vector ?

标签 c++ vector

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 错误:binary '==': no operator found which takes a left-hand operand of type 'g'。

最佳答案

你应该为你的类实现==操作符:

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});

关于c++ - 如何使用 std::find 作为类 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59501380/

相关文章:

c++ - 案例内部的功能

c++ - 减去 X.begin() 如何返回迭代器的索引?

c++ - 使用指针实例化类

c++ - 如何将 vector 重新排列为列而不是行?

c++ - 将 pop_front 实现为 std::vector 的快速方法

java - 通过网络发送对象 vector

c++ - C/C++ 的广泛执行

c++ - 未定义对 WinMain 的引用,[错误] ID 返回 1 退出状态

c++ - 推力装置 vector 推力装置 vector <int>

xml - 如何在r中将向量输出到xml