📜  用C++对向量排序

📅  最后修改于: 2021-05-30 12:18:44             🧑  作者: Mango

先决条件:C++中的std :: sort,C++中的vector,C++中的vector初始化。

// C++ program to sort a vector in non-decreasing
// order.
#include 
using namespace std;
  
int main()
{
    vector v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
  
    sort(v.begin(), v.end());
  
    cout << "Sorted \n";
    for (auto x : v)
        cout << x << " ";
  
    return 0;
}

输出 :

Sorted 
0 1 2 3 4 5 6 7 8 9 

如何按降序排序?
sort()采用第三个参数,该参数用于指定元素的排序顺序。我们可以传递“ greater()”函数以降序排列。该函数进行比较的方式是将更大的元素放在前面。

// C++ program to sort a vector in non-increasing
// order.
#include 
using namespace std;
  
int main()
{
    vector v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
  
    sort(v.begin(), v.end(), greater());
  
    cout << "Sorted \n";
    for (auto x : v)
        cout << x << " ";
  
    return 0;
}

输出 :

Sorted 
9 8 7 6 5 4 3 2 1 0 

如何按特定顺序排序?
我们还可以编写自己的比较器函数并将其作为第三个参数传递。

// A C++ program to sort vector using
// our own comparator
#include 
using namespace std;
  
// An interval has start time and end time
struct Interval {
    int start, end;
};
  
// Compares two intervals according to staring times.
bool compareInterval(Interval i1, Interval i2)
{
    return (i1.start < i2.start);
}
  
int main()
{
    vector v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
  
    // sort the intervals in increasing order of
    // start time
    sort(v.begin(), v.end(), compareInterval);
  
    cout << "Intervals sorted by start time : \n";
    for (auto x : v)
        cout << "[" << x.start << ", " << x.end << "] ";
  
    return 0;
}

输出 :

Intervals sorted by start time : 
[1, 9] [2, 4] [4, 7] [6, 8] 

相关文章 :对向量排序|套装1
对向量排序|套装2

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”