最小最大值和置换运算

原文:https://www.studytonight.com/cpp/stl/stl-min-max-operations-cont

以下是我们将要介绍的函数,因为我们在上一课中已经介绍了 STL 中最小和最大操作的其他方法。

  • 最小最大值法
  • 最小最大元素法
  • next _ 置换方法
  • 预排列法

minmaxminmax_element方法

minmax 方法的语法是:minmax(object_type a ,object_type b)

该方法返回一对,其中对的第一个元素是 ab 的较小元素,对的第二个元素是 ab 的较大元素。如果 a 和 b 都相等,那么 minmax 返回一对 < a,b > 。minmax 仅在 C++ 11 及以上版本中提供。

下面是一个演示 minmax()方法用法的示例。

#include<iostream>
#include<algorithm>
#include<numeric>

using namespace std;

int main()
{
    pair<int,int> **p**;

    p = **minmax**(2,3);
    */* now p.first = 2 ( smaller element ) 
    And p.second = 3 ( larger element )   */* 

    pair<string,string> **p2**;

    p2 = **minmax**("abcd" , "abce");
    */* p2.first = "abcd" ( lexicographically smaller string )
    And p2.second = "abce" (lexicographically larger string )  */*

    p =  **minmax**(2,2);
    */* p.first = p.second = 2 , */*

    /* minmax can also be used for number of elements */

    p = **minmax**({2,6,5,4,9,8});
    /* now p.first = 2 ( smaller element ) 
    And p.second = 9 ( larger element )   */ 
}

minmax_element方法的语法是:minmax_element(iterator first, iterator last, compare_function)

此方法返回一对迭代器,其中第一个元素指向范围[第一个,最后一个]中的最小元素,第二个元素指向范围[第一个,最后一个]中的最大元素。

下面是一个演示 minmax_element()用法的示例。

#include<iostream>
#include<algorithm>
#include<array>
using namespace std;

int main ()
{
    array<int,7> **foo** {3,7,2,9,5,8,6};

    auto **result** = **minmax_element**(foo.begin(), foo.end());

    *// print result:*
    cout << "min is " << *result.first;
    cout << "max is " << *result.second;
    return 0;
}

next_permutationprev_permutation方法

next _ 置换方法的语法是:

next_permutation(iterator first ,iterator last)

此方法在下一个字典式的较大排列中排列范围[第一个,最后一个]中的元素。长度范围 n 内的元素,有 n!(阶乘)元素排列的可能方式,每种排列称为一种排列

prev_permutation方法的语法是:

prev_permutation(iterator first, iterator last)

此方法将范围[第一个,最后一个]中的元素排列在下一个字典式较小的排列中。

下面是一个演示 max_element()和 min_element()方法用法的示例。

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

using namespace std;

int main () 
{
    char s[] = "abcd";
    **next_permutation**(s, s+4);
    cout << s >> endl;
    */* prints "abdc" */*

    **rev_permutation**(s, s+4);
    cout << s >> endl;
    */* prints "dcba" */*

    int a[] = {1,2,3,4};

    **next_permutation**(a, a+4);
    */* now a is 1,2,4,3  */*

    vector<int> v(a, a+4);
    */* v is : 1,2,4,3  */*

    **next_permutation**(v.begin(), v.end() );
    */* now v is : 1,3,2,4 */*

    */* resetting a[] for prev_permutation */*
    int a[] = {1,2,3,4};

    **prev_permutation**(a, a+4);
    */* now a is 4,3,2,1  */*

    vector<int> v(a, a+4);
    */* v is : 4,3,2,1  */*
    **prev_permutation**(v.begin(), v.end());
    */* now v is : 4,3,1,2 */*

    return 0;
}