[英]How to sort a pair of vector in some given range
我知道如何使用std:sort(v.begin(), v.end());
对向量进行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[i]
制作一对向量。 例如 - first_array = {1, 5, 4, 9}
和second_array = {2, 10, 5, 7}
那么对的向量将是size = 2*size_of(first/second array)并且元素将是[{1, 2}, {5, 10}, {4, 5}, {9, 7}]
。 然后我根据对的第二个元素(即第二个数组的所有元素)按降序对这些对进行排序。
现在我想对第二个元素相等的向量形式进行排序。
例如 - 如果向量是[{1,6} , {4,5}, {3,5}, {8,5}, {1,1}]
。 这里 5 在 pair 的第二个元素中出现 3 次,因此按升序对它们的第一个索引进行排序。 预期结果 - [{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;
}
您需要的是以下内容
#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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.