Doubt about sort syntax

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <algorithm>
#include <vector>

int main( int argc, char* argv[] )
{
    std::vector<int> 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <algorithm>
#include <vector>

int main( int argc, char* argv[] )
{
    std::vector<int> my_vec = { 1, 10, 2, 50, 7, 6 };

    std::vector<int>::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.