题目1431:Sort

题目描述:

给你n个整数,请按从大到小的顺序输出其中前m大的数。

输入:

每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数。

输出:

对每组测试数据按从大到小的顺序输出前m大的数。

样例输入:
5 3
3 -35 92 213 -644
样例输出:
213 92 3
#include <cstdio>
#include <queue>
#include <vector>
#include <functional>

using namespace std;

int main()
{
    int n, m;

#ifndef ONLINE_JUDGE
    freopen("d:\\OJ\\uva_in.txt", "r", stdin);
#endif

    while (scanf("%d%d", &n, &m) == 2) {
        priority_queue<int, vector<int>, greater<int> > pq;

        for (int i = 0; i < n; i++) {
            int num;
            scanf("%d", &num);
            if (pq.size() < m) {
                pq.push(num);
            } else if (num > pq.top()) {
                pq.pop();
                pq.push(num);
            }
        }

        vector<int> v;
        while (!pq.empty()) {
            int num = pq.top(); pq.pop();
            v.push_back(num);
        }

        printf("%d", v[v.size() - 1]);
        for (int i = v.size() - 2; i >= 0; i--) {
            printf(" %d", v[i]);
        }
        printf("\n");

    }
    return 0;
}

import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.Scanner;
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.Stack;

class Main
{
	public static final boolean DEBUG = false;
	
	public static void main(String[] args) throws IOException
	{
		Scanner cin;
		int n, m;
		
		if (DEBUG) {
			cin = new Scanner(new FileReader("d:\\OJ\\uva_in.txt"));
		} else {
			cin = new Scanner(new InputStreamReader(System.in));
		}
		
		while (cin.hasNext()) {
			n = cin.nextInt();
			m = cin.nextInt();
			PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
			
			for (int i = 0; i < n; i++) {
				int num = cin.nextInt();
				if (pq.size() < m) {
					pq.add(num);
				} else {
					if (num > pq.peek()) {
						pq.poll();
						pq.add(num);
					}
				}
			}
			
			int[] ans = new int[pq.size()];
			int cnt = 0;
			while (!pq.isEmpty()) {
				ans[cnt++] = pq.poll().intValue();
			}
			
			System.out.print(ans[cnt - 1]);
			for (int i = cnt - 2; i >= 0; i--) {
				System.out.print(" " + ans[i]);
			}
			System.out.println();
		}
	}
}


<think>嗯,用户现在问的是关于在C++中使用std::sort进行自定义升序排列。之前他们问了绝对值的问题,我详细介绍了不同据类型的处理,现在他们可能在学习排序相关的知识。 首先,我需要确认用户的需求。他们可能已经知道std::sort的基本用法,现在想了解如何自定义排序规则,特别是升序排列。不过,通常升序是默认行为,所以用户可能实际上是想了解如何自定义比较函,比如降序或者根据特定条件排序,但题目里明确说是“自定义升序”,可能需要解释如何覆盖默认行为或者处理自定义类型的排序。 接下来,我需要回顾std::sort的用法。std::sort默认使用operator<来排序,所以升序是默认的。但用户提到“自定义升序”,可能是指对自定义据结构或者特定排序规则进行调整。比如,按照对象的某个成员变量升序排列,或者有特殊比较逻辑。 然后,我应该考虑用户可能的实际应用场景。比如,他们可能有一个结构体或类,需要根据其中的某个字段进行排序。或者他们可能需要处理非默认据类型的排序,比如字符串按照长度排序,但同时保持升序。这时候就需要自定义比较函。 需要详细说明如何传递自定义比较函给std::sort,包括函指针、lambda表达式、函对象等。同时,要注意比较函的规则,即严格弱序,以及如何正确实现它以避免未定义行为。 可能还需要提到性能方面的考虑,比如lambda表达式内联的可能性,或者函对象的优势。此外,错误处理也是重要的,比如比较函必须满足的条件,否则会导致运行时错误。 用户之前的问题涉及头文件和命名空间的使用,所以在回答中也应该包含必要的头文件(比如<algorithm>)和使用std命名空间的注意事项,或者显式使用std::前缀。 还要提供示例代码,让用户能够直观地理解如何应用自定义排序。例如,对一个自定义的Person结构体按年龄升序排列,或者对字符串按长度排序,同时保持长度相同的按字典序排列。 另外,需要注意用户可能的误区,比如误以为升序需要显式指定,而实际上默认就是升序。但根据问题描述,用户可能想了解如何自定义,所以重点应放在自定义逻辑上,而不仅仅是使用默认行为。 最后,总结关键点,强调比较函的设计和传递方式,确保用户能够正确应用自定义排序规则,并避免常见错误。</think>在 C++ 中,`std::sort` 默认对容器元素进行**升序排列**,但可以通过**自定义比较函**实现更灵活的排序逻辑。以下是具体用法和示例: --- ### 1. **基本用法(默认升序)** - **适用场景**:直接对基本据类型(如 `int`, `double`, `string` 等)升序排列。 - **代码示例**: ```cpp #include <algorithm> #include <vector> int main() { std::vector<int> nums = {3, 1, 4, 1, 5}; std::sort(nums.begin(), nums.end()); // 默认升序:1, 1, 3, 4, 5 } ``` --- ### 2. **自定义升序规则** 当需要为**自定义类型**或**特定比较逻辑**实现升序时,需定义比较函(或 Lambda 表达式)。 #### **方式 1:函指针** - **示例**:按字符串长度升序排列 ```cpp #include <algorithm> #include <vector> #include <string> bool compareLength(const std::string& a, const std::string& b) { return a.length() < b.length(); // 长度短的在前 } int main() { std::vector<std::string> words = {"apple", "cat", "banana"}; std::sort(words.begin(), words.end(), compareLength); // 结果:"cat", "apple", "banana" } ``` #### **方式 2:Lambda 表达式(推荐)** - **示例**:对结构体按年龄升序排列 ```cpp #include <algorithm> #include <vector> struct Person { std::string name; int age; }; int main() { std::vector<Person> people = {{"Alice", 25}, {"Bob", 20}, {"Charlie", 30}}; std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) { return a.age < b.age; // 年龄小的在前 }); // 结果:Bob(20), Alice(25), Charlie(30) } ``` #### **方式 3:函对象(仿函)** - **示例**:按绝对值升序排列 ```cpp #include <algorithm> #include <vector> struct CompareAbs { bool operator()(int a, int b) const { return std::abs(a) < std::abs(b); // 绝对值小的在前 } }; int main() { std::vector<int> nums = {-3, 2, -1, 4}; std::sort(nums.begin(), nums.end(), CompareAbs()); // 结果:-1, 2, -3, 4 } ``` --- ### 3. **核心规则** - **比较函返回值**: - 返回 `true`:表示 `a` 应该排在 `b` 前面。 - 返回 `false`:表示 `a` 不应排在 `b` 前面。 - **严格弱序要求**: - 必须满足传递性(若 `a < b` `b < c`,则 `a < c`)。 - 不可出现 `a < a`(即 `compare(a, a)` 必须为 `false`)。 --- ### 4. **注意事项** 1. **性能优化**:优先使用 Lambda 表达式或函对象(仿函),避免函指针(可能无法内联优化)。 2. **头文件**:必须包含 `<algorithm>`。 3. **容器支持**:仅适用于随机访问迭代器(如 `vector`, `deque`, 普通组等)。 --- ### 5. **复杂示例:多条件排序** ```cpp // 按字符串长度升序,长度相同时按字典序升序 std::vector<std::string> words = {"apple", "cat", "banana", "dog"}; std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { if (a.length() != b.length()) { return a.length() < b.length(); // 第一条件:长度 } else { return a < b; // 第二条件:字典序 } }); // 结果:"cat", "dog", "apple", "banana" ``` --- ### 总结 - **默认升序**:直接使用 `std::sort(begin, end)`。 - **自定义升序**: - 函指针:适合简单逻辑。 - Lambda 表达式:灵活易读(推荐)。 - 仿函:适合重复使用的复杂逻辑。 - **严格弱序**:必须遵守,否则导致未定义行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值