标签:style blog class code c ext
partial_sort接受一个middle迭代器,使序列中的middle-first个最小元素以递增顺序排序,置于[first, middle)内。下面是测试代码:
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int a[] = {10,9,8,7,6,5,4,3,2,1,0}; vector<int> vec(a, a+11); vector<int>::iterator b = vec.begin(); vector<int>::iterator e = vec.end(); partial_sort(b, b+6, e); // 前6个最小元素排序 while (b != e) cout << *(b++) << ‘ ‘; return 0; }
template <class RandomAccessIterator> inline void partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last) { __partial_sort(first, middle, last, value_type(first)); }
template <class RandomAccessIterator, class T> void __partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, T*) { make_heap(first, middle); // [first, middle)区间构造一个heap for (RandomAccessIterator i = middle; i < last; ++i) if (*i < *first) // 当前元素比堆中最大的元素小 __pop_heap(first, middle, i, T(*i), distance_type(first)); // first值放i中,i的原值融入heap并调整 sort_heap(first, middle); }
template <class RandomAccessIterator, class T, class Distance> inline void __pop_heap(RandomAccessIterator first, RandomAccessIterator last, RandomAccessIterator result, T value, Distance*) { *result = *first; // 弹出元素放vector尾端 __adjust_heap(first, Distance(0), Distance(last - first), value); }
template <class RandomAccessIterator> void sort_heap(RandomAccessIterator first, RandomAccessIterator last) { while (last - first > 1) pop_heap(first, last--); }
算法 — partial_sort,布布扣,bubuko.com
标签:style blog class code c ext
原文地址:http://blog.csdn.net/nestler/article/details/25882261