c++ - 使用 std::nth_element 时,第 n 个元素的拷贝是否总是连续的?

标签 c++ sorting contiguous quickselect nth-element

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,但我的 vector 中有重复项。目前我正在使用 nth_element 来查找中值。问题是选择一个独特的/可重构的中位数,而不必再次遍历 vector 。如果中值是连续的,我可以选择一个唯一的中值,而无需太多遍历。

最佳答案

没有。 documentation没有指定这种行为,经过几分钟的实验,很容易找到一个测试用例,其中受骗者在 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

如果 dupes 是连续的,则输出将是 2

关于c++ - 使用 std::nth_element 时,第 n 个元素的拷贝是否总是连续的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30369272/

相关文章:

c - 如何在 c 中创建具有连续 ID 的线程?

python - 查找 nan 填充数组的固定长度连续区域(无重叠)

c++ - 如何用 C/++ 编写一个简单的编译器?

c++ - ‘[’ 标记之前的预期主表达式

c++ - 数组大小不定

c++ - 帮助使用 std::locale?

algorithm - 确定排序数组是否包含总和为 N 的连续序列

c++ - 字符串转换错误

Java SuperClass 和 SubClass 扩展可比较

java - 如何读取以逗号分隔的名称列表 Java