Home > Software engineering >  error C2676 binary '==': 'block' does not define this operator or a conversion t
error C2676 binary '==': 'block' does not define this operator or a conversion t

Time:12-16

#include <iostream>
#include <vector>

using namespace std;

class block {
public:
    int x, y;
    block(int in_x = 0, int in_y = 0) {
        x = in_x;
        y = in_y;
    }
    int get_x() {
        return x;
    }
    int get_y() {
        return y;
    }
    void set_x(int in_x) {
        x = in_x;
    }
    void set_y(int in_y) {
        y = in_y;
    }
};

int main() {
    int x = 5; int y = 5;
    vector<block> blocks = vector <block>();
    for (int i = 0; i < x; i  ) {
        for (int j = 0; j < y; j  ) {
            block p;
            p.set_x(i);
            p.set_y(j);
            blocks.push_back(p);
        }
    }
    //Search block 1,1 in vector
    block b;
    b.set_x(1);
    b.set_y(1);

    vector< block>::iterator item;
    item = find(blocks.begin(), blocks.end(), b);
    if (item !=blocks.end())
    {
        cout << endl << "Element found";
        return true;
    }
    else
    {
        cout << endl << "Element not found";
        return false;
    }
}

I am running this code and I am getting this error.

error C2676 binary '==': 'block' does not define this operator or a conversion to a type acceptable to the predefined operator

The answer might be obvious, but I cannot understand where the problem is, because the error doesn't specify a line. It might be incorrect use of iterator and vector::find(), but I am not sure.

I tried:

    block *b=new block;
    b->set_x(1);
    b->set_y(1);

    vector< block>::iterator item;
    item = find(blocks.begin(), blocks.end(), *b);

But I am getting the same mistake.

CodePudding user response:

Your block class lacks an operator== to allow 2 block objects to be compared for equality. std::find() uses that operator when comparing objects in the specified range.

You need to add that operator to your class, eg:

class block {
public:
    int x, y;
    ...
    bool operator==(const block &rhs) const {
        return x == rhs.x && y == rhs.y;
    }
};

Alternatively:

class block {
public:
    int x, y;
    ...
};

bool operator==(const block &lhs, const block &rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y;
}
  • Related