📜  逆序排序向量 c++ (1)

📅  最后修改于: 2023-12-03 15:41:56.931000             🧑  作者: Mango

逆序排序向量

在C++中,我们可以使用向量(vector)作为动态数组,并使用STL库提供的sort函数进行排序操作。

但是,有时我们需要对向量进行逆序排序。下面,我们将介绍如何实现逆序排序向量。

方法一

使用STL库提供的sort函数,同时自定义比较函数。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool cmp(int a, int b) {
    return a > b;  // 逆序排序
}

int main() {
    vector<int> v = {3, 5, 1, 7, 2};
    sort(v.begin(), v.end(), cmp);  // 调用sort函数,传入自定义比较函数
    for (int i : v) {
        cout << i << " ";
    }
    return 0;
}

输出:

7 5 3 2 1

在上述代码中,我们定义了一个cmp函数,其中返回a > b,即当a大于b时,返回true,实现逆序排序。在调用sort函数时,将cmp函数作为第三个参数传入即可。

方法二

使用STL库提供的reverse函数,翻转向量。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<int> v = {3, 5, 1, 7, 2};
    sort(v.begin(), v.end());  // 先对向量进行排序
    reverse(v.begin(), v.end());  // 翻转向量
    for (int i : v) {
        cout << i << " ";
    }
    return 0;
}

输出:

7 5 3 2 1

在上述代码中,我们先使用sort函数对向量进行排序,再使用reverse函数翻转向量,实现逆序排序。

总结

以上即为两种实现逆序排序向量的方法。使用自定义比较函数的方法可用于所有可排序的数据结构,而使用翻转向量的方法则非常简便,但需要先进行排序操作。

建议使用自定义比较函数的方法,因为这种方法处理数据时更优雅、更灵活易用。