Hey everybody i have a quick question about the sort() command.

I know that when i want to sort the whole vector from the beginning to the end i have to write sort(vector.begin(), vector.end());

But what would it be like if I wanted to sort it from position i to position j?

Thanks!
Just pass in whatever iterator locations you need.

 ``123456789101112131415`` ``````#include #include #include int main( int argc, char* argv[] ) { std::vector my_vec = { 1, 10, 2, 50, 7, 6 }; std::sort( my_vec.begin() + 2, my_vec.begin() + 5 ); for( const auto &i : my_vec ) std::cout << i << " "; return 0; }``````

You could easily store the iterators as variables and pass them in.

 ``1234567891011121314151617181920`` ``````#include #include #include int main( int argc, char* argv[] ) { std::vector my_vec = { 1, 10, 2, 50, 7, 6 }; std::vector::iterator sort_start, sort_end; sort_start = my_vec.begin() + 1; sort_end = my_vec.end() - 1; std::sort( sort_start, sort_end ); for( const auto &i : my_vec ) std::cout << i << " "; return 0; }``````

As long as your position i and position j are iterator types for the vector then you can just pass those in.
Last edited on
Sort just the sub-range [position i, position j) :
`std::sort( vec.begin()+i, vec.begin()+j ) ;`

Partial sort (place the sorted smallest i elements of the vector at the beginning):
`std::partial_sort( vec.begin(), vec.begin()+i, vec.end() ) ;`
http://en.cppreference.com/w/cpp/algorithm/partial_sort

Also see: http://en.cppreference.com/w/cpp/algorithm/nth_element

Last edited on
Topic archived. No new replies allowed.