前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >STL中的nth_element()方法的使用

STL中的nth_element()方法的使用

作者头像
Angel_Kitty
发布2018-04-08 16:54:48
6250
发布2018-04-08 16:54:48
举报
文章被收录于专栏:小樱的经验随笔

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

代码语言:javascript
复制
 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 }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-04-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档