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;
}- A. It compiles; keys are compared memberwise
- B. It compiles; keys are compared by address
- C. It compiles but throws at run time
- 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
- What is printed? cpp int main() { vector<int> a(3, 5), b{3, 5}; cout << a.size() << a[0] << b.size() << b[0]; }
- What is printed? cpp void f(int a[10]) { cout << (sizeof(a) == sizeof(int)); } int main() { int arr[10]; cout << sizeof(arr) /…
- What is printed? cpp struct S { int next() { static int c = 0; return ++c; } }; int main() { S a, b; a.next(); b.next(); cout << a.next(); }
- What is printed? cpp int main() { try { throw "oops"; } catch (string& s) { cout << "S"; } catch (const char s) { cout << s; } }
- Which line fails to compile? cpp struct A { A(int) { } }; struct B { explicit B(int) { } }; A f() { return 5; } // L1 B g() { return 5; }…
- Which line fails to compile? cpp int main() { int a[3] = {1, 2, 3}, b[3]; b = a; // L1 array<int, 3> c{1, 2, 3}, d; d = c; // L2 }