使用std::nth_element时,第n个元素的副本总是连续的

Are duplicates of the nth element always contiguous when using std::nth_element?

本文关键字:元素 副本 连续 nth std element 使用      更新时间:2023-10-16
vector<int> data = {3, 1, 5, 3, 3, 8, 7, 3, 2}; 
std::nth_element(data.begin(), data.begin() + median, data.end());

这将总是导致:

data = {less, less, 3, 3, 3, 3, larger, larger, larger} ?

或者其他可能的结果是:

data = {3, less, less, 3, 3, 3, larger, larger, larger} ?

我已经在我的机器上尝试了多次,结果第n个值总是连续的。但这不是证据;)。

用途:

我想建立一个唯一的Kdtree但是我的向量中有重复的。目前,我使用nth_element来查找中值。问题是选择一个唯一的/可重构的中间值,而不必再次遍历向量。如果中间值是连续的,我可以选择一个唯一的中间值,而不需要遍历。

No。文档没有指定这样的行为,并且经过几分钟的实验,很容易找到一个测试用例,其中副本在ideone上不连续:

#include <iostream>
#include <algorithm>
int main() {
    int a[] = {2, 1, 2, 3, 4};
    std::nth_element(a, a+2, a+5);
    std::cout << a[1];
    return 0;
}
输出:

1

如果副本是连续的,输出将是2

我刚刚尝试了几个不太简单的例子,在第三个例子中得到了不连续的输出。

项目

#include <vector>
#include <iostream>
#include <algorithm>
int main() {
   std::vector<int> a = {1, 3, 3, 2, 1, 3, 5, 5, 5, 5};
   std::nth_element(a.begin(), a.begin() + 5, a.end());
   for(auto v: a) std::cout << v << " ";
   std::cout << std::endl;
}

与gcc 4.8.1在Linux下,与std=c++11,给我输出

3 1 1 2 3 3 5 5 5 5

而第n个元素是3。

所以不,元素并不总是连续的

我还认为,即使是更简单的方法,不考虑一个好的测试用例,只是生成长随机数组与许多重复的元素,并检查它是否成立。我想它会在第一次或第二次尝试时破裂。