整数奇偶数排序:奇数从大到小在前,偶数从小到大在后(stable_partition的应用)

Description
  给定10个整数的序列,要求对其重新排序。排序要求:1.奇数在前,偶数在后;2.奇数按从大到小排序;3.偶数按从小到大排序。

Input
  输入一行,包含10个整数,彼此以一个空格分开,每个整数的范围是大于等于0,小于等于100。

Output
  按照要求排序后输出一行,包含排序后的10个整数,数与数之间以一个空格分开。

Sample Input:4 7 3 13 11 12 0 47 34 98
Sample Output :47 13 11 7 3 0 4 12 34 98

1、介绍stable_partition

stable_partition是c++排序函数的一个分支,用于将满足某一特定规则的部分放在最前面。 比如此题要求将奇数放在前面,偶数放在后面。

2、操作步骤

stable_partition的应用形式为:

vector<int>::iterator it=stable_partition(a.begin(),a.end(),cmp);

cmp是一个比较函数:

bool cmp(int &x) {
    
     
	return x % 2;   //奇数放在前面 
}

返回1即x为奇数,即将奇数放在前面,返回的it为后半部分开始的位置,即偶数开始的位置。

3、本题思路分析

使用stable_partition将奇数放在前面,偶数放在后面,再分别对两部分使用sort函数,前半部分从大到小,后半部分从小到大。

4、AC代码

#include<bits/stdc++.h>
using namespace std;

vector<int> a;

bool cmp(int &x) {
    
     
	return x % 2;   //奇数放在前面 
}

int main() {
    
    
	int t;
    for(int i = 0; i < 10; i++) {
    
    
      cin >> t;
      a.push_back(t);
    }
    vector<int>::iterator it=stable_partition(a.begin(),a.end(),cmp);
    sort(a.begin(), it, greater<int>());
    sort(it, a.end(), less<int>());
    for(vector<int>::iterator iter=a.begin(); iter!=a.end(); iter++) {
    
    
   	  cout << *iter << ' ';
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cyril_KI/article/details/109557671