No a std::vector
is not sorted using merge sort (in most implementations; the standard doesn't specify the algorithm).
std::list
does not have O(1) random access, so it cannot use algorithms like Quick sort* which requires O(1) random access to be fast (this is also why std::sort
doesn't work on std::list
.)
With this, you'll have to use algorithms that forward iteration is enough, such as the Merge sort**.
And merge sort is typically slower [1][2].
See also: what's the difference between list.sort and std::sort?
*: libstdc++ actually uses introsort.
**: libstdc++ actually uses a variant of merge sort
The sort
function requires something that can be called with two arguments and returns a bool, this could be a lambda function:
sort( list.begin( ), list.end( ),
[]( const samplestruct& a, const samplestruct&b ){
return a.Name < b.Name;
} );
By default it looks for an operator<
, so this would work as well:
bool operator<( const samplestruct& a, const samplestruct&b ){
return a.Name < b.Name;
}
sort( list.begin( ), list.end( ) );
Best Answer
You can define what comparison function to use in each run of the sort algorithm by using the third argument:
A simple example: