對給定範圍進行"排序"
說明,參數,返回值,實例,
說明
模板函式
頭檔案: <algorithm>
函式名: std::nth_element
(1) | template <class RandomAccessIterator> void nth_element (RandomAccessIterator first, RandomAccessIterator nth,RandomAccessIterator last); |
---|---|
(2) | template <class RandomAccessIterator, class Compare> void nth_element (RandomAccessIterator first, RandomAccessIterator nth,RandomAccessIterator last, Compare comp); |
對給定範圍內的元素"排序"
對給定範圍[first,last)內的元素進行重新布置.方法是,nth位置的元素放置的值就是把所有元素排序後在nth位置的值.把所有不大於nth的值放到nth的前面,把所有不小於nth的值放到nth後面.
參數
- first, last
- 隨機訪問疊代器.指定了需要重新"排序"的範圍.包括first,但不包括last.
- nth
- 隨機訪問疊代器.指向範圍[first,last)內的一個位置.這個位置將放置排序後應該放於此位置的元素.
comp
二元函式. 返回bool. 表明是否第一個參數應該排序到第二個參數的前面.此函式不應該修改參數值.可以是一個函式指針或函式對象.
返回值
無
實例
//nth_elementexample#include<iostream>//std::cout#include<algorithm>//std::nth_element,std::random_shuffle#include<vector>//std::vectorboolmyfunction(inti,intj){return(i<j);}intmain(){std::vector<int>myvector;//setsomevalues:for(inti=1;i<10;i++)myvector.push_back(i);//123456789std::random_shuffle(myvector.begin(),myvector.end());//usingdefaultcomparison(operator<):std::nth_element(myvector.begin(),myvector.begin()+5,myvector.end());//usingfunctionascompstd::nth_element(myvector.begin(),myvector.begin()+5,myvector.end(),myfunction);//printoutcontent:std::cout<<"myvectorcontains:";for(std::vector<int>::iteratorit=myvector.begin();it!=myvector.end();++it)std::cout<<''<<*it;std::cout<<'\n';return0;}