ProgrammingHardProduct-company placement · C++
std::sort(v.begin(), v.end(), [](int a, int b) { return a <= b; }); What is wrong with this call?
- A. Nothing; it sorts in ascending order
- B. It sorts in descending order
- C. The comparator is not a strict weak ordering (it returns true for equal elements), so the behaviour is undefined
- D. It fails to compile because sort needs operator<
Correct answer: C. The comparator is not a strict weak ordering (it returns true for equal elements), so the behaviour is undefined
std::sort requires comp(a, a) to be false. With <=, equal elements compare 'less' both ways, which can make the algorithm read out of bounds or produce garbage; use < instead.
More OOP with C++ and Java questions
- What is printed? cpp int main() { priorityqueue<int> a; priorityqueue<int, vector<int>, greater<int>> b; for (int x : {3, 1, 4}) {…
- What happens when this is compiled? cpp struct Pt { int x, y; }; int main() { map<Pt, int> m; m[{1, 2}] = 5; }
- 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; } }