i am reading the book--"The C++ Standard Library -
A Tutorial And Reference (1999)"(haven't finished it yet)
I quite wonder how could the std::sort is possible?
At line X, befoure I overwrite the value of *it2 to *minIt
I have to save the value of *minIt
But I don't know how to declare a variable to save the value
of *minIt, do you have any ideas to solve this?
Why do you want to save the value of *minIt?
I think that you need to do std::swap( *minIt, *it2 );. However you better work with iterators as long as you can, that's the copy of objects and might be costly.
PS:I try not to use the algorithm of stl to implement selSort
I want to realize how to implement something similar to stl
Because stl are quite cool for me
I hope someday I could design something like the way stl did
Still have a long way to go...
But by writing your own Swap() method you reduce the generality of your sort function.
It would be best to do this:
1 2 3 4 5 6 7 8 9
template< typename Iter >
void selection_sort( Iter first, Iter last )
{
using std::swap;
// ...
swap( *it, *minIt );
}
In this way, you allow the user to implement their own swap function for their type, and if they don't provide one, the default std::swap gets used instead.
Your way, the user is sorta forced to use your Swap function.
Also, for even more generality, you could provide an overload that allows the user to specify a comparator.
1 2 3 4 5 6 7 8 9 10
template< typename Iter, typename Compare >
void selection_sort( Iter first, Iter last, Compare comp )
{
using std::swap;
// ...
if( comp( *it2, *minIt ) )
swap( *it2, *minIt );
// ...
}