1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. std::sort(v.begin(), v.end(), [](int a, int b){ return a…

Added 30 Nov -0001

std::sort(v.begin(), v.end(), [](int a, int b){ return a >= b; }); is called. What is the defect?

  1. std::sort needs a function pointer, so a lambda cannot be used as the predicate
  2. The predicate is fine, but it makes std::sort fall back to a stable bubble sort
  3. The predicate is not a strict weak ordering, so the sort behaviour is undefined Correct answer
  4. The predicate sorts descending, which std::sort rejects with a compile error

Correct answer

C. The predicate is not a strict weak ordering, so the sort behaviour is undefined

15 views

MCQSEXAM

Explanation

Strict weak ordering requires irreflexivity, so comp(x, x) must be false; with a >= b the algorithm may read out of bounds, and the standard declares the behaviour undefined. Descending order should be written a > b. Debug builds of libstdc++ with _GLIBCXX_DEBUG often catch this as an assertion about the comparator, while release builds may return a silently wrong order.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs