c++ - 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.
解决方案
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.
推荐阅读
- angular - 导航链接需要点击 2 次才能响应
- sql - 如何计算 PostgreSQL 中出现连续行的总时间
- mysql - 'group by' 操作后如何获取某条记录
- java - 获取错误 java.lang.NoClassDefFoundError: org/mockito/MockitoAnnotations$Mock
- c# - 将 WPF DataGrid 导出为 CSV 时修剪值
- azure - 将内部 VNET 中的 API 管理与应用程序网关集成
- robotframework - Store Variable Of Response in RobotFramework
- php - 如何处理 php artisan queue:listen
- php - 获取PHP数组中对象的元素
- wordpress - WordPress 商店页面