1

I have two vectors, a, b, of structs abc and abc2 respectively:

struct abc {
    const int &data;
    abc(const int& cdata) : data(cdata) {}
};

struct abc2 {
    const int& data;
    abc2(const int& cdata) : data(cdata) {}

    bool operator== (const abc& c1) const {
        return (c1.data == data);
    }
};

int main() {

    std::vector<abc> a{abc(2), abc(2)};
    std::vector<abc2> b{abc2(2), abc2(2)};

}

And I want to see if a and b are equal.

However when I attempt the following:

assert(a == b);

I get a compile time error of

Error C2678 binary '==': no operator found which takes a left-hand operand of type 'std::vector<abc,std::allocator<_Ty>>' (or there is no acceptable conversion) with [ _Ty=abc ]

How can I implement a custom equality check for these two vectors of different types? I do not ever need to do abc == abc2 so a overload equals operator is not required for the abc struct.

1
  • The dupe seems to answer the question in your title. Is that what you're looking for, or are you trying to actually get == to work? Commented Nov 4, 2020 at 18:59

1 Answer 1

1

There is a standard algorithm for comparing equality: std::equal. In this case

assert(std::equal(b.begin(), b.end(), a.begin(), a.end()));
Sign up to request clarification or add additional context in comments.

2 Comments

You can use an overload of std::equal that takes four iterators instead of checking sizes explicitly.
@Evg Oh nice, they added those in C++14.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.