ProgrammingHardProduct-company placement · C++

What happens when this is compiled?

What happens when this is compiled?
struct Pt { int x, y; };
int main() {
    map<Pt, int> m;
    m[{1, 2}] = 5;
}
  1. A. It compiles; keys are compared memberwise
  2. B. It compiles; keys are compared by address
  3. C. It compiles but throws at run time
  4. D. Compile-time error: no operator< for Pt (std::less<Pt> cannot compare keys)

Correct answer: D. Compile-time error: no operator< for Pt (std::less<Pt> cannot compare keys)

std::map orders its keys with std::less<Key>, which needs operator<. Pt defines none, so the comparison fails to compile; provide operator< or a custom comparator.

More OOP with C++ and Java questions

Exams that ask this topic