首页 > 解决方案 > 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. 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.

标签: c++sortingvector

解决方案


The second parameter (last) is pointing one past the last element that should be sorted. So when the iterators you pass to sort are

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.


推荐阅读