在C ++ 11中复制恒定大小数组的最干净方法 [英] Cleanest way to copy a constant size array in 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屋!