zoukankan      html  css  js  c++  java
  • STL之nth_element()(取容器中的第n大值)

     nth_element仅排序第n个元素(从0开始索引),即将位置n(从0开始)的元素放在第n大的位置,处理完之后,默认排在它前面的元素都不比它大,排在它后面的元素都不比它小。

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 int main()
     5 {
     6     int a[] = { 1,3,4,15,2,6,8,7,9 };
     7     int i;
     8     cout << "数列例如以下:" << endl;
     9     for (i = 0; i<9; i++)
    10         cout << a[i] << " ";
    11     nth_element(a, a + 5, a + 6);
    12     cout << endl << "输出第五大的数: " << a[4] << endl; //注意下标是从0開始计数的 
    13     return 0;
    14 }

    运行结果:

    https://www.cnblogs.com/yxwkf/p/5233716.html

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 int main()
     5 {
     6     //int a[] = { 1,3,4,15,2,6,8,7,9 };
     7     //int i;
     8     //cout << "数列例如以下:" << endl;
     9     //for (i = 0; i<9; i++)
    10     //    cout << a[i] << " ";
    11     //nth_element(a, a + 5, a + 6);
    12     //cout << endl << "输出第五大的数: " << a[4] << endl; //注意下标是从0開始计数的 
    13 
    14     int a[10];
    15     for (int i = 0; i<10; ++i) {
    16         a[i] = i;
    17     }
    18     random_shuffle(a, a + 10);
    19     for (int i = 0; i<10; ++i) std::cout << a[i] << ' '; std::cout << '
    ';
    20     nth_element(a, a + 6, a + 10);
    21     for (int i = 0; i<10; ++i) std::cout << a[i] << ' '; std::cout << '
    ';
    22 
    23     return 0;
    24 }

  • 相关阅读:
    BZOJ3631 [JLOI2014] 松鼠的新家
    HDU
    HDU
    HDU
    二分图求最大独立集模板
    HDU
    HDU
    HDU
    Codeforces 1197F Coloring Game 矩阵快速幂 (看题解)
    HDU
  • 原文地址:https://www.cnblogs.com/thebreakofdawn/p/9609122.html
Copyright © 2011-2022 走看看