STL中的nth_element()方法的使用

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

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 }

 

目录
相关文章
|
22天前
|
前端开发
内部样式表(style元素)
内部样式表(style元素)。
22 2
|
5月前
|
存储 算法 对象存储
【C++11算法】minmax和minmax_element
【C++11算法】minmax和minmax_element
|
数据可视化 JavaScript
element-plus 树形控件用法
element-plus 树形控件是一种常用的可视化组件,可以展示树型结构的数据。以下是 element-plus 树形控件的用法。
509 0
|
前端开发
css中:nth-child()和nth-of-type有何区别详解
css中:nth-child()和nth-of-type有何区别详解
|
前端开发
css选择器nth-child和nth-of-type区别
css选择器nth-child和nth-of-type区别
css选择器nth-child和nth-of-type区别
|
前端开发 JavaScript 开发者
Element scrollbar 使用封装
最近进行 Element UI 组件封装,在之前的项目中经常用到 el-scrollbar这个内置组件,这次单独封装时遇到点写法上的小问题,做个记录和分享,希望能帮到相关的开发者。
171 0
Element scrollbar 使用封装
|
人工智能 C++
STL中nth_element的用法
nth_element函数原型有四个,详细我就不一一累赘了,我们就用最普通的用法寻找第k位置的元素。 函数用法为:nth_element(first,kth,end)。 first,last 第一个和最后一个迭代器,也可以直接用数组的位置。
1964 0
|
算法 C#
算法题丨Remove Element
描述 Given an array and a value, remove all instances of that value in-place and return the new length.
1040 0