STL中的nth_element()方法的使用

STL中的nth_element()方法的使用 通过调用nth_element(start, start+n, end)
方法可以使第n大元素处于第n位置(从0开始,其位置是下标为
n的元素),并且比这个元素小的元素都排在这个元素之前,比这个元素大的元素都排在这个元素之后,但不能保证他们是有序的,下面是这个方法的具体使用方法.

复制代码
 1 #include <iostream>
 2 
 3 #include <algorithm>
 4 
 5 #include <functional>
 6 
 7 #include <vector>
 8 
 9 using namespace std;
10 
11 
12 
13 int main()
14 
15 {
16 
17     const int VECTOR_SIZE = 50 ;
18 
19 
20 
21     vector<int> Numbers(VECTOR_SIZE) ;
22 
23 
24 
25     vector<int>::iterator start, end, it ;
26 
27 
28 
29     // Initialize vector Numbers
30 
31     for(int i=0;i<50;++i){
32 
33              Numbers[i]=i;
34 
35     }
36 
37 /*由于赋值时是有序的,下面random_shuffle()方法将这些数据的顺序打乱*/
38 
39     random_shuffle(Numbers.begin(),Numbers.end());
40 
41     
42 
43 // location of first element of Numbers
44 
45     start = Numbers.begin() ; 
46 
47 
48 
49  // one past the location last element of Numbers
50 
51     end = Numbers.end() ;     
52 
53 
54 
55     cout << "Before calling nth_element/n" << endl ;
56 
57 
58 
59   // print content of Numbers
60 
61     cout << "Numbers { " ;
62 
63     for(it = start; it != end; it++)
64 
65         cout << *it << " " ;
66 
67     cout << " }/n" << endl ;
68 
69 
70 
71   /* 
72 
73     * partition the elements by the 8th element,
74 
75   *(notice that 0th is the first element)
76 
77   */ 
78 
79     nth_element(start, start+8, end) ;
80 
81 
82 
83     cout << "After calling nth_element/n" << endl ;
84 
85 
86 
87     cout << "Numbers { " ;
88 
89     for(it = start; it != end; it++)
90 
91         cout << *it << " " ;
92 
93     cout << " }/n" << endl ;
94 
95     system("pause");
96 
97 }
复制代码

 

posted @   Angel_Kitty  阅读(3292)  评论(5编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示
剑桥
14:14发布
剑桥
14:14发布
6°
南风
3级
空气质量
相对湿度
87%
今天
多云
4°/16°
周日
9°/18°
周一
大雨
8°/15°