📌  相关文章
📜  C++中对对的排序向量设置2(按降序排列,依次为第一和第二)

📅  最后修改于: 2021-04-28 13:53:55             🧑  作者: Mango

我们已经讨论了以下集合1中对向量对排序的一些情况。
C++中对对的排序向量设置1(按第一和第二的顺序排序)
本文讨论了更多案例
有时我们需要按相反的顺序对向量进行排序。在这些情况下,与其先对向量进行排序,然后再使用“反向”函数,不如增加代码的时间复杂度。因此,为避免这种情况,我们直接按降序对向量进行排序。
情况3:基于对的第一个元素以降序对向量元素进行排序。
这种类型的排序将向量中选定的成对的行按降序排列。这是通过使用“ sort()”并传递一维向量的迭代器作为其参数来实现的。

CPP
// C++ program to demonstrate sorting in vector of
// pair according to 1st element of pair in
// descending order
#include
using namespace std;
 
int main()
{
    // declaring vector of pairs
    vector< pair  > vect;
 
    // initializing 1st and 2nd element of
    // pairs with array values
    int arr[] = {5, 20, 10, 40 };
    int arr1[] = {30, 60, 20, 50};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    // Entering values in vector of pairs
    for (int i=0; i


CPP
// C++ program to demonstrate sorting/in vector of
// pair according to 2nd element of pair in
// descending order
#include
using namespace std;
 
// Driver function to sort the vector elements by
// second element of pair in descending order
bool sortbysecdesc(const pair &a,
                   const pair &b)
{
       return a.second>b.second;
}
 
 
int main()
{
    // Declaring vector of pairs
    vector< pair  > vect;
 
    // Initializing 1st and 2nd element of
    // pairs with array values
    int arr[] = {5, 20, 10, 40 };
    int arr1[] = {30, 60, 20, 50};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    // Entering values in vector of pairs
    for (int i=0; i


输出:

The vector before applying sort is:
5 30
20 60
10 20
40 50
The vector after applying sort is:
40 50
20 60
10 20
5 30



情况4:根据对的第二个元素以降序对向量元素进行排序。
也可以通过修改“ sort()”函数并将调用再次传递给用户定义的函数来处理这些实例。

CPP

// C++ program to demonstrate sorting/in vector of
// pair according to 2nd element of pair in
// descending order
#include
using namespace std;
 
// Driver function to sort the vector elements by
// second element of pair in descending order
bool sortbysecdesc(const pair &a,
                   const pair &b)
{
       return a.second>b.second;
}
 
 
int main()
{
    // Declaring vector of pairs
    vector< pair  > vect;
 
    // Initializing 1st and 2nd element of
    // pairs with array values
    int arr[] = {5, 20, 10, 40 };
    int arr1[] = {30, 60, 20, 50};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    // Entering values in vector of pairs
    for (int i=0; i

输出:

The vector before sort operation is:
5 30
20 60
10 20
40 50
The vector after applying sort operation is:
20 60
40 50
5 30
10 20



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