Reputation: 1921
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 ?
Upvotes: 2
Views: 3947
Reputation: 4617
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.
Upvotes: 1
Reputation: 6546
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).
Upvotes: 1
Reputation: 310980
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 );
Upvotes: 3
Reputation: 170084
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.
Upvotes: 7