我知道如何使用對向量進行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}然后對的所述的載體將是大小= 2 * size_of(第一/第二陣列)和元素會[{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}]
注意 - 我們已經按降序對第二個元素進行了排序。
uj5u.com熱心網友回復:
您必須更新排序功能。嘗試這個。
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;
}
演示
uj5u.com熱心網友回復:
您需要的是以下內容
#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 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/339873.html
上一篇:按日期列對角材料表進行排序
