C ++ array replication

C ++ style copy operation

Using the copy algorithm in STL

int a[] = {1,2,3,4,5};
int b[5];
std::copy(std::begin(a),std::end(a),std::begin(b));
for(auto e:b) cout<<e<<" ";     // 输出 1,2,3,4,5

In the above procedure, copy algorithm will replicate the array to a segment interval to begin (b) starting to go.

Use array containers (C ++ 11)

std::array<int,5> arr = {1,2,3,4,5};
std::array<int,5> copy;
copy = arr;      // 将arr中的元素复制到copy中
arr[0] = 100;
for(auto e:copy) cout<<e<<" ";      //输出 1,2,3,4,5

C-style copy operation

Use memcpy ()

int arr[] = {1,2,3,4,5};
int copy[5];
int len = sizeof(arr) / sizeof(arr[0]);
memcpy(copy,arr,len*sizeof(int));   // 输出 1,2,3,4,5
for(auto e:copy) cout<<e<<" ";

Note: memcpy () function indicates the third parameter is the number of bytes to copy, not the number of elements to be copied. As for the reason for this, we can look at memcpy () prototype:
void* memcpy(void* destination,const void* source,size_t num);

Can be seen from memcpy () function prototype, types of the first two parameters of the function is of type void *, this is done in order to make memcpy () can be applied to any type of pointer.

But this has led to a problem that memcpy () do not know how much of each element of the array incoming bytes used to represent. It is also for this reason, such memcpy () The third argument is the number of elements can not be copied, but the number of bytes to be copied.

Use memmove ()

This function is memcpy () is similar, but the source and destination memmove allow overlapping positions, for example:

int arr[] = {1,2,3,4,5,6,7,8};
memmove(arr+3,arr+1,sizeof(int)*5);
for(auto e:arr) cout<<e<<" ";       // 输出 1,2,3,2,3,4,5,6

Note: the above procedure, if the memmove () for as memcpy () might also work, but this behavior is unpredictable, when the destination position overlapping the source, should be used memmove ().

Transfer: https://www.techforgeek.info/how_to_copy_array.html

Guess you like

Origin www.cnblogs.com/clwsec/p/11600899.html