使用 stdnth 元素查詢中位數(或其他分位數)
所述 std::nth_element
演算法需要三個迭代器:一個迭代開始時, N 個位置,並結束。一旦函式返回,第 n 個元素(按順序)將是第 n 個最小元素。 (該函式具有更復雜的過載,例如,一些採用比較函子;請參閱上面的連結瞭解所有變體。)
注意此功能非常有效 - 它具有線性複雜性。
為了這個例子,讓我們將長度為 n 的序列的中位數定義為位置為⌈n/2⌉的元素。例如,長度為 5 的序列的中值是第 3 個最小元素,長度為 6 的序列的中值也是如此。
要使用此函式查詢中位數,我們可以使用以下內容。假設我們開始
std::vector<int> v{5, 1, 2, 3, 4};
std::vector<int>::iterator b = v.begin();
std::vector<int>::iterator e = v.end();
std::vector<int>::iterator med = b;
std::advance(med, v.size() / 2);
// This makes the 2nd position hold the median.
std::nth_element(b, med, e);
// The median is now at v[2].
為了找到第 p 個分位數 ,我們將改變上面的一些行:
const std::size_t pos = p * std::distance(b, e);
std::advance(nth, pos);
並在 pos
處尋找分位數。