Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

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

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?

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?

like image 990
bobbaluba Avatar asked Sep 08 '12 05:09

bobbaluba


People also ask

How do you copy an array value?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.

How do you include an array in C++?

As expected, an n array must be declared prior its use. A typical declaration for an array in C++ is: type name [elements]; where type is a valid type (such as int, float ...), name is a valid identifier and the elements field (which is always enclosed in square brackets [] ), specifies the size of the array.


2 Answers

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; 
like image 102
Benjamin Lindley Avatar answered Oct 02 '22 00:10

Benjamin Lindley


The C++03 way

Use std::copy():

float a[4] = {0,1,2,3}; float b[4];  std::copy(a,a + 4, b); 

That's about as clean as it gets.

The C++11 way

std::copy(std::begin(a), std::end(a), std::begin(b)); 

If you can use std::array

With std::array you just do simple assignment:

std::array<float,4> a = {0,1,2,3}; auto b = a; 
like image 30
Mysticial Avatar answered Oct 02 '22 00:10

Mysticial