I know how to sort pair of vectors using std:sort(v.begin(), v.end());
But this will sort all the pairs of the vector.
But I want to sort the vector in a specified range.
#include<bits/stdc++.h>
#define ll long long
using namespace std;
bool sortbysecdesc(const pair<int,int> &a,const pair<int,int> &b)
{
return a.second>b.second;
}
int main(){
int n;
cin>>n;
ll a[n];
ll b[n];
vector<pair<ll, ll>> v;
vector<pair<ll, ll>>::iterator itr;
for (int i = 0; i < n; i++) {
cin>>a[i];
}
for (int i = 0; i < n; i++) {
cin>>b[i];
}
for (int i = 0; i < n; i++) {
v.push_back(make_pair(a[i],b[i]));
}
//sorting the pair in descending order with second element
sort(v.begin(), v.end(), sortbysecdesc);
for (itr=v.begin(); itr!=v.end(); itr++) {
/* Logic to be implement */
}
return 0;
}
Code explanation- Here I'm taking input 2 arrays and making a pair of vector by combining first_array[i]
element with second_element[i]
element.
Such as - first_array = {1, 5, 4, 9}
and second_array = {2, 10, 5, 7}
then the vector of pair's will be of size = 2*size_of(first/second array) and elements will be [{1, 2}, {5, 10}, {4, 5}, {9, 7}]
.
Then I'm sorting these pair in descending order according to second elements of pairs i.e, all elements of second array.
Now I wanna sort the vector form where second elements are equal.
eg - if the vector is [{1,6} , {4,5}, {3,5}, {8,5}, {1,1}]
. Here 5 occurs three time in second element of pair so sort their first index in ascending order.
Expected result - [{1,6} , {3,5}, {4,5}, {8,5}, {1,1}]
Note - We had already sorted the second element in descending order.