在 C++11 中复制常量大小数组的最简洁方法 [英] Cleanest way to copy a constant size array in c++11

查看:35
本文介绍了在 C++11 中复制常量大小数组的最简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己想要复制具有恒定大小的数组的内容,我通常只是按照以下方式编写:

I often find myself wanting to copy the contents of arrays that have a constant size, I usually just write something along the lines of:

float a[4] = {0,1,2,3};
float b[4];

for(int i=0; i<4; i++){
    b[i]=a[i];
}

最近,我正在编写一个用于教育目的的线性微积分库,我想知道是否有更好的方法来做到这一点.

As of lately, I am writing a linear calculus library for educational purposes, and I was wondering if there was a better way to do it.

我首先想到的是使用 memcpy:

The first thing that came to my mind, was using memcpy:

memcpy(b, a, sizeof(float) * 4);

但这对我来说似乎很像 c 并且容易出错.我喜欢在编译时出现错误,对于具有非平凡复制构造函数的数据类型,或者如果我忘记与 sizeof(datatype) 相乘,这可能会变得丑陋.

But this seems very c-like and error prone to me. I like having my errors at compile time, and this can get ugly for data types with non-trivial copy constructors, or if I forget to multiply with sizeof(datatype).

由于我正在编写一个我将大量使用的数学库,因此性能对我来说非常重要.今天的编译器是否足够聪明,能够理解第一个示例只是复制一块内存并对其进行优化以使其与第二个解决方案一样高效?

Since I am writing a math library that I am going to use intensively, performance is very important to me. Are the compilers today smart enough to understand that the first example is just copying a chunk of memory and optimize it to be as efficient as the second solution?

也许标准库中有一个函数可以帮助我?C++11 中的新东西?还是我应该只创建一个宏或模板函数?

Perhaps there is a function in the standard library that can help me? Something new in c++11? Or should I just create a macro or a template function?

推荐答案

如果您使用 std::array 而不是内置数组(您应该这样做),它会变得非常简单.复制数组与复制任何其他对象相同.

If you use std::array instead of a built-in array (which you should), it becomes very simple. Copying an array is then the same as copying any other object.

std::array<float,4> a = {0,1,2,3};
std::array<float,4> b = a;

这篇关于在 C++11 中复制常量大小数组的最简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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