In C++, the std::forward_list
is a single-linked list that allows for efficient insertion and deletion of elements. However, it does not provide random access iterators, which means that sorting can be a bit more challenging compared to vector or list. To sort elements in a std::forward_list
, you can use the std::sort
and std::stable_sort
algorithms. However, note that these algorithms require random access iterators, so they cannot be applied directly to std::forward_list
. Instead, you can transfer elements to a container that supports random access, sort them, and then transfer them back.
Here’s an example that demonstrates how to sort and stable sort a std::forward_list
by first moving its elements to a std::vector
:
#include <iostream>
#include <forward_list>
#include <vector>
#include <algorithm>
int main() {
std::forward_list flist = {5, 3, 2, 8, 1};
// Copy elements to a vector
std::vector vec(flist.begin(), flist.end());
// Sort the vector
std::sort(vec.begin(), vec.end());
// Transfer sorted elements back to forward_list
flist.clear();
flist.insert_after(flist.before_begin(), vec.begin(), vec.end());
std::cout << "Sorted forward_list: ";
for (int n : flist) {
std::cout << n << " ";
}
std::cout << std::endl;
// Using stable_sort
// Clear the forward_list and add same elements again
flist = {5, 3, 2, 8, 1};
std::vector vec2(flist.begin(), flist.end());
// Sort using stable_sort
std::stable_sort(vec2.begin(), vec2.end());
// Transfer sorted elements back to forward_list
flist.clear();
flist.insert_after(flist.before_begin(), vec2.begin(), vec2.end());
std::cout << "Stable sorted forward_list: ";
for (int n : flist) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?