如何快速与1真正的大数组初始化 [英] How to fast initialize with 1 really big array

查看:122
本文介绍了如何快速与1真正的大数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有enermous数组:

I have enermous array:

int* arr = new int[BIGNUMBER];

如何使用1号fullfil它的真快。通常我会做

How to fullfil it with 1 number really fast. Normally I would do

for(int i = 0; i < BIGNUMBER; i++)
    arr[i] = 1

但我认为这将需要很长时间。

but I think it would take long.

我可以使用的memcpy 或类似的?

推荐答案

您可以尝试使用标准功能的 的std :: uninitialized_fill_n

You could try using the standard function std::uninitialized_fill_n:

#include <memory>

// ...

std::uninitialized_fill_n(arr, BIGNUMBER, 1);

在任何情况下,当涉及到性能,规则是要始终进行测量来备份你的假设 - 特别是如果你要放弃一个清晰的,简单的设计拥抱,因为据称性能提升的更复杂的

In any case, when it comes to performance, the rule is to always make measurements to back up your assumptions - especially if you are going to abandon a clear, simple design to embrace a more complex one because of an alleged performance improvement.

编辑:

注意 - <一个href=\"http://stackoverflow.com/questions/16385453/how-to-fast-initialize-with-1-really-big-array/16385478?noredirect=1#comment23484620_16385478\">as本杰明·林德利在评论中提到 - 为了微不足道的类型的std :: uninitialized_fill_n 不会带来任何优势比较明显的 的std :: fill_n 。其优点会存在非平凡的类型,因为的std ::的uninitialized_fill 将允许你分配一块内存区域,然后在地方构造对象。

Notice that - as Benjamin Lindley mentioned in the comments - for trivial types std::uninitialized_fill_n does not bring any advantage over the more obvious std::fill_n. The advantage would exist for non-trivial types, since std::uninitialized_fill would allow you to allocate a memory region and then construct objects in place.

不过,人们不应该落入陷阱调用的std :: uninitialized_fill_n 因为这是一个存储区的的未初始化的。以下,例如,将给予未定义行为:

However, one should not fall into the trap of calling std::uninitialized_fill_n for a memory region that is not uninitialized. The following, for instance, would give undefined behavior:

my_object* v = new my_object[BIGNUMBER];
std::uninitialized_fill_n(my_object, BIGNUMBER, my_object(42)); // UB!

这篇关于如何快速与1真正的大数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆