As the title says, I'm looking for a way to sort a vector without modifying the original one. My first idea is of course to create a copy of the vector before the sort, e.g.:
std::vector<int> not_in_place_sort(const std::vector<int>& original)
{
auto copy = original;
std::sort(copy.begin(), copy.end());
return copy;
}
However, maybe there is a more efficient way to perform the sort using C++ standard algorithm (maybe a combination of sort
and transform
?)
Use partial_sort_copy. Here is an example:
vector<int> v{9,8,6,7,4,5,2,0,3,1};
vector<int> v_sorted(v.size());
partial_sort_copy(begin(v), end(v), begin(v_sorted), end(v_sorted));
Now, v remains untouched but v_sorted contains {0,1,2,3,4,5,6,7,8,9}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With