Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to sort a vector leaving the original one unaltered?

Tags:

c++

sorting

stl

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?)

like image 655
Emiliano Avatar asked Nov 28 '17 17:11

Emiliano


1 Answers

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}.

like image 160
Erel Segal-Halevi Avatar answered Sep 18 '22 07:09

Erel Segal-Halevi