Junior — Middle
Can the std::sort function be used to sort a standard list in C++?
sobes.tech AI
Answer from AI
The std::sort function from the C++ standard library requires that the container provides random access to elements (Random Access Iterator). The standard std::list is implemented as a doubly linked list and provides only bidirectional iterators (Bidirectional Iterator), so std::sort cannot be used with it.
For sorting std::list, there is a built-in method list::sort(), which implements sorting suitable for doubly linked lists. Example:
#include <list>
#include <iostream>
int main() {
std::list<int> lst = {4, 2, 5, 1, 3};
lst.sort(); // sort the list
for (int n : lst) {
std::cout << n << ' ';
}
return 0;
}
If you need to sort the elements of a std::list using std::sort, you can copy them into a vector, sort it, and then copy back, but this is less efficient.