C/C++ 数组复制
分几种情况:
1.字符数组
使用strcpy
2.int,float,double等数组
使用memcpy,如复制一个长度为5 的 float数组,则代码示例如下
int len = 5;
float a[len] = {1.0 ,1.1, 1.2, 1.3, 1.4};
float b[len];
memset(b, 0, len*sizeof(float));
memcpy(b, a, len * sizeof(float));
注意,第三个参数不是指数组个数,而是指要复制的数据的总字节数长度。
3.对象数组
不能使用以上两种,需要实现拷贝构造函数或赋值重载函数。
C++ 风格的复制操作
使用STL中的copy算法
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<
使用array容器 (C++11) 由memcpy()的函数原型可以看到,该函数的前两个参数的类型是void*类型,这样做是为了使memcpy()可以作用于任何类型的指针。 但这样做又导致了一个问题,即memcpy()不知道传入数组的每个元素用多少字节来表示。也正是因为这个原因,使得memcpy()的第三个参数不能是要复制的元素个数,而是要复制的字节数。 使用memmove() int arr[] = {1,2,3,4,5,6,7,8}; 测试实例
std::array
std::array
copy = arr; // 将arr中的元素复制到copy中
arr[0] = 100;
for(auto e:copy) cout<
C 风格的复制操作
使用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<
void* memcpy(void* destination,const void* source,size_t num);
该函数与memcpy()类似,只是memmove允许目的位置和源位置重叠,示例如下:
memmove(arr+3,arr+1,sizeof(int)*5);
for(auto e:arr) cout<
#include
using namespace std;
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[10] = { 0 };
int c[10] = { 0 };
//copy
copy(begin(a), end(a), begin(b));
for (auto i : b)
cout << i << " ";
cout << endl;
//memcpy
memcpy(c, a, sizeof(a));
for (auto i : c)
cout << i << " ";
cout << endl;
//memmove
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
memmove(arr + 3, arr + 1, sizeof(int)* 5);
for (auto e : arr)
cout << e << " ";
cout << endl;
system("pause");
return 0;
}
运行结果: