简体   繁体   English

向量的部分排序(就地)

[英]Sorting part of vector (in place)

I could not understand why below piece of code is not sorting first two elements of vector : 我不明白为什么下面的代码没有对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 ? 有什么想法吗 ?

std::sort (and all standard library algorithms) expects a half-open range. std::sort (和所有标准库算法)期望半开范围。 The end iterator is a one-past end indicator (the open part). 结束迭代器是一个过去的结束指示器(开放部分)。 So [it, it + 1) is a range of just one element. 因此[it, it + 1)的范围仅为一个元素。 In your case, it's just the first vector element. 在您的情况下,它只是第一个向量元素。

And well, a one element range is already sorted. 而且,一个元素范围已经排序。

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 . 可以像[v.begin(), v.begin() + 1 )那样数学写的范围v.begin(),v.begin()+1仅包含一个等于2元素v[0] If you want to sort a range of 2 elements then you should write 如果要对2个元素进行排序,则应编写

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

that is equivalent to 相当于

std;:sort( v.begin(), v.begin() + 2 );
Sorts the elements in the range [first, last) 

from std::sort 来自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 . 如果您不熟悉该表示法,则)表示不包括last ,您可以在此问题中找到有关该信息的更多信息。

In order to sort first n elements you must indicate you call as follows: 为了对前n个元素进行排序,必须指示您按以下方式进行调用:

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

Thus for 2 elements you must call: 因此,对于2个元素,您必须调用:

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

This is because all STL algorithms takes open range [first, last). 这是因为所有STL算法都采用开放范围(第一个,最后一个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM