有没有办法将nth_element与数据副本一起完成?
Is there a way to do nth_element together with copy of data?
我希望从C++的浮点数组中计算中值:
float Median( FloatArray const * constFloatArray )
{
FloatArray scratch = FloatArray( *constFloatArray );
int64_t const size = scratch.GetWidth() * scratch.GetHeight();
int64_t const mid = size / 2;
std::nth_element( scratch.begin(), scratch.begin() + mid, scratch.end() );
return scratch[ mid ];
}
FloatArray 包含一个常规的 C++ 浮点数组。
我正在使用std::nth_element
但想知道是否有像nth_element
这样的工具可以使用const
数据? 现在,我正在制作一份副本,然后在扔掉副本之前做nth_element
。 如果const
数据没有类似nth_element
的东西,是否有更有效的方法使用复制步骤来计算信息,从而避免潜在的额外 O(n( 循环? 也许性能影响可以忽略不计? 我的阵列大小可能在 20 亿左右。
我不确定它是否会更有效率,但您可以使用std::partial_sort_copy
节省一半的复制。 我们可以使用std::partial_sort_copy
仅将一半的数据复制到一个新数组中,它会在这样做时将其排序到该数组中。 然后,您需要做的就是获取奇数个元素的最后一个元素,或者偶数个元素的最后两个元素的平均值。 使用看起来像
int main()
{
std::vector<int> v{5, 6, 4, 3, 2, 6, 7, 9, 3, 10};
std::vector<int> r(v.size() / 2 + 1);
std::partial_sort_copy(v.begin(), v.end(), r.begin(), r.end());
if (r.size() % 2)
std::cout << r.back();
else
std::cout << (r[r.size() - 1] + r[r.size() - 2]) / 2.0;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 使用流处理接收到的数据
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在cuda线程之间共享大量常量数据
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中序列化结构数据
- 如何避免将数据缓冲区的额外副本复制到字符串?
- 有没有办法将nth_element与数据副本一起完成?
- 如何将char数据附加到std :: vector而不会导致副本
- 给定一个填充无符号字符**的 C 函数,如何在没有中间副本的情况下用数据填充 std::vector
- 为什么初始化列表会导致2个数据副本,而不仅仅是单个副本将其传递给函数
- 矢量和指针队列数据交换:深层和浅层副本
- 指针是否可能在没有任何数据副本的情况下被向量所拥有
- 将std::字符串数据的深层副本存储到std::vector中
- 对指针向量进行排序会更改该向量副本中的数据
- 面试编码-将指向节点结构的指针作为参数,并返回传入数据结构的完整副本
- 为什么在初始化列表中不需要创建额外的副本就可以对数据进行赋值