函式模板
<algorithm>

std::partial_sort_copy

預設 (1)
template <class InputIterator, class RandomAccessIterator>  RandomAccessIterator    partial_sort_copy (InputIterator first,InputIterator last,                       RandomAccessIterator result_first,                       RandomAccessIterator result_last);
自定義 (2)
template <class InputIterator, class RandomAccessIterator, class Compare>  RandomAccessIterator    partial_sort_copy (InputIterator first,InputIterator last,                       RandomAccessIterator result_first,                       RandomAccessIterator result_last, Compare comp);
複製並部分排序範圍
將範圍 [first,last) 中的最小元素複製到 [result_first,result_last),並對複製的元素進行排序。複製的元素數量與 result_firstresult_last 之間的 距離 相同(除非此數量大於 [first,last) 中的元素數量)。

範圍 [first,last) 不會被修改。

元素使用第一個版本的 operator< 進行比較,第二個版本使用 comp 進行比較。

引數

first, last
輸入迭代器,指向要從中複製的序列的起始和結束位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
InputIterator 應指向一個 可賦值RandomAccessIterator 所指向的元素型別的型別。
result_first, result_last
隨機訪問迭代器,指向目標序列的起始和結束位置。使用的範圍是 [result_first,result_last)
RandomAccessIterator 應指向一個為其定義了 swap,並且同時是 可移動構造可移動賦值 的型別。
comp
二進位制函式,接受結果範圍中的兩個元素作為引數,並返回一個可轉換為 bool 的值。返回的值指示傳遞給第一個引數的元素是否被認為在其定義的特定 嚴格弱序 中排在第二個元素之前。
該函式不得修改其任何引數。
這可以是指向函式的指標,也可以是函式物件。

返回值

一個指向結果序列中最後一個寫入元素的下一個元素的迭代器。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// partial_sort_copy example
#include <iostream>     // std::cout
#include <algorithm>    // std::partial_sort_copy
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }

int main () {
  int myints[] = {9,8,7,6,5,4,3,2,1};
  std::vector<int> myvector (5);

  // using default comparison (operator <):
  std::partial_sort_copy (myints, myints+9, myvector.begin(), myvector.end());

  // using function as comp
  std::partial_sort_copy (myints, myints+9, myvector.begin(), myvector.end(), myfunction);

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

輸出
myvector contains: 1 2 3 4 5


複雜度

平均而言,比 firstlast 之間的 距離 的對數複雜度略高:執行大約 N*log(min(N,M)) 次元素比較(其中 N 是該距離,Mresult_firstresult_last 之間的 距離)。它還執行高達此數量的元素交換(或移動)以及 min(N,M) 次範圍之間的賦值。

資料競爭

範圍[first,last)內的物件將被修改。

異常

如果任何元素比較、元素賦值、元素交換(或移動)或迭代器操作引發異常,則丟擲異常。
請注意,無效引數會導致未定義行為

另見