ProgrammingHardProduct-company placement · C++

std::sort(v.begin(), v.end(), [](int a, int b) { return a <= b; }); What is wrong with this call?

  1. A. Nothing; it sorts in ascending order
  2. B. It sorts in descending order
  3. C. The comparator is not a strict weak ordering (it returns true for equal elements), so the behaviour is undefined
  4. 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

Exams that ask this topic