J Xkcd
J Xkcd

Reputation: 423

How to use std::find for a class 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);
}

This code gives me a C2678 error: binary '==': no operator found which takes a left-hand operand of type 'g' .

Upvotes: 0

Views: 70

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

You can use a lambda and the standard algorithm std::find_if.

If I have correctly understood your code then you need something like

int  x = 2;
auto it = find_if( f.begin(), 
                   f.end(), 
                   [x]( const g &item ) 
                   { 
                       return item.x == x || item.y == x || item.z == x;
                   } );

Upvotes: 0

VLL
VLL

Reputation: 10155

You should implement == operator for your class:

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

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

Use correct type as the parameter:

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

Upvotes: 1

Related Questions