简体   繁体   English

std::sort() 函数无法对向量的一部分进行排序

[英]std::sort() function not able to sort a part of a vector

The std::sort function is somehow not able to sort a particular part of a vector. std::sort函数以某种方式无法对向量的特定部分进行排序。 The upper bound and lower bound of the part of the vector to be sorted are entered as inputs along with size of vector and vector elements.要排序的向量部分的上限和下限与向量和向量元素的大小一起作为输入输入。 This is what I've tried:这是我尝试过的:

#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;

int main()
{
    long long int N,L,R;
    cin>>N;
    vector <long long int> V;
    while(N--)
    {
        long long int input;
        cin>>input;
        V.push_back(input);
    }
        cin>>L>>R;
        sort(V.begin()+L-1,V.begin()+R-1);
        vector<long long int>::iterator I = V.begin();
        while(I<V.end())
        {
            cout << *I << " ";
            I++;
        }
        cout << endl;
}

My input:
5      
3 -1 4 2 -1
3 4

Expected output:
3 -1 2 4 -1

Actual output:
3 -1 4 2 -1 (unchanged)

Kindly tell what is incorrect in this approach/ what other method can be applied.请告诉这种方法有什么不正确/可以应用哪些其他方法。

The second parameter ( last ) is pointing one past the last element that should be sorted.第二个参数 ( last ) 指向应该排序的最后一个元素。 So when the iterators you pass to sort are所以当你传递给 sort 的迭代器是

3 -1 4 2 -1 
     ^-------- first
       ^------ last

Then there is only a single element in the range to be sorted and the output you get is to be expected.然后在要排序的范围内只有一个元素,您得到的输出是可以预期的。

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

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