我知道如何使用std:sort(v.begin(), v.end());
对向量进行排序,但这将对向量的所有对进行排序。但是我想在指定的范围内对向量进行排序。
#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;
}
代码解释-这里我输入2个数组,并通过将first_array[i]
元素与second_element[i]
元素组合成一对向量。如-first_array = {1, 5, 4, 9}
和second_array = {2, 10, 5, 7}
,则pair的向量为size = 2*size_of(第一/第二数组)和元素将是[{1, 2}, {5, 10}, {4, 5}, {9, 7}]
。然后我将这些对按照对的第二个元素的降序排序也就是第二个数组的所有元素
现在我要对第二个元素相等的向量形式进行排序
eg -如果向量是[{1,6} , {4,5}, {3,5}, {8,5}, {1,1}]
。这里5在pair的第二个元素中出现了三次,所以将它们的第一个索引按升序排序。预期结果-[{1,6} , {3,5}, {4,5}, {8,5}, {1,1}]
注意-我们已经按降序对第二个元素进行了排序。
您需要的是如下内容
#include <tuple>
#include <vector>
#include <iterator>
#include <algorithm>
//...
std::sort( std::begin( v ), std::end( v ),
[]( const auto &p1, const auto &p2 )
{
return std::tie( p2.second, p1.first ) < std::tie( p1.second, p2.first );
} );
这是一个示范程序。
#include <iostream>
#include <tuple>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<std::pair<long long, long long>> v =
{
{1,6} , {4,5}, {3,5}, {8,5}, {1,1}
};
std::sort( std::begin( v ), std::end( v ),
[]( const auto &p1, const auto &p2 )
{
return std::tie( p2.second, p1.first ) <
std::tie( p1.second, p2.first );
} );
for ( const auto &p : v )
{
std::cout << "{ " << p.first << ", " << p.second << " } ";
}
std::cout << 'n';
return 0;
}
程序输出为
{ 1, 6 } { 3, 5 } { 4, 5 } { 8, 5 } { 1, 1 }
您必须更新您的排序函数。试试这个。
bool sortbysecdesc(const pair<int,int> &a,const pair<int,int> &b)
{
return a.second == b.second ? a.first < b.first : a.second > b.second;
}
演示