Below is my code

template<typename iterator>
void selSort(iterator begin, iterator end)
{
  iterator minIt = begin;  
  iterator it2 = begin + 1;   
  for(iterator it = begin; it != end; ++it)
  {
    minIt = it;
    for(; it2 != end; ++it2)
    {
      if(*it2 < *minIt)
        *minIt = *it2;  //line X
    }
    std::swap(it2, minIt);
  }
}

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?

Thanks a lot

Recommended Answers

All 2 Replies

> But I don't know how to declare a variable to save the value of *minIt

typename std::iterator_traits<iterator>::value_type saved_value = *minIt ;

See: http://www.sgi.com/tech/stl/iterator_traits.html

Do you really need it?

template< typename iterator >
void selection_sort( iterator begin, iterator end )
{
    if( begin != end ) 
    {
       // find the minimum value in [ begin, end ),
       // and swap it with the value at begin
       std::iter_swap( begin, std::min_element( begin, end ) ) ;

       // repeat for [ begin+1, end )
       selection_sort( ++begin, end ) ;
    }
}

Thanks a lot, yeah, I don't need it.
Forgive my immature

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.