2

I could not understand why below piece of code is not sorting first two elements of vector :

int main() {
    std::vector<int> v = {2,1,3,1,2};
    std::sort(v.begin(),v.begin()+1);
    for(auto elem:v)
    {
      std::cout<<elem<<std::endl;
    }
    // your code goes here
    return 0;
}

Any thoughts ?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
PapaDiHatti
  • 1,841
  • 19
  • 26

4 Answers4

6

std::sort (and all standard library algorithms) expects a half-open range. The end iterator is a one-past end indicator (the open part). So [it, it + 1) is a range of just one element. In your case, it's just the first vector element.

And well, a one element range is already sorted.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
3

This range v.begin(),v.begin()+1 that can be mathematically written like [v.begin(), v.begin() + 1 ) contains only one element v[0] that is equal to 2. If you want to sort a range of 2 elements then you should write

std::sort( v.begin(), std::next( v.begin(), 2 ) );

that is equivalent to

std;:sort( v.begin(), v.begin() + 2 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1
Sorts the elements in the range [first, last) 

from std::sort

In case you are not familiar with the notation, ) means last is not included, you can find more information about that in this question.

Mansuro
  • 4,558
  • 4
  • 36
  • 76
1

In order to sort first n elements you must indicate you call as follows:

sort(V.begin(), V.begin() + n);

Thus for 2 elements you must call:

 sort(V.begin(), V.begin() + 2);

This is because all STL algorithms takes open range [first, last).

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76