I am using a vector with my class type A
as its element type. I defined the relational operator <
for my class but when I compare two of these vectors it crashes.
class A {
public:
explicit A(int){}
bool operator<(const A&)const {
return true; // for simplicity
}
};
int main() {
std::vector<A> v{ A(1), A(2), A(3), A(4), A(5) };
std::vector<A> v2{ A(0), A(2), A(4), A(6) };
std::cout << (v < v2) << std::endl; // program crashes here!
}
I am trying to understand this because I've read that the STL containers use the element type's relational operator?!
the program runs fine on GCC but on MSVC++ 14 it crashes so I get the assertion dialog complaining about the line
std::cout << (v < v2) << std::endl; // program crashes here!
The most interesting thing as @user4581301 pointed out is if I define the relational operator correctly it solves the problem:
class A { public: explicit A(int) {} bool operator<(const A& a)const { return x < a.x; // for simplicity } int x; };
Now it works fine and the program doesn't crash! Is this some restriction in MSVC++? (I mean defining the operator correctly?)