C++ 数组拷贝:std::copy 和 std::memcpy 的使用方法
C++ 数组拷贝:std::copy 和 std::memcpy 的使用方法
在 C++ 中,您可以使用 std::copy 算法或 std::memcpy 函数来拷贝数组内容。
使用 std::copy 算法:
#include <algorithm>
#include <iostream>
int main() {
int sourceArray[] = {1, 2, 3, 4, 5};
int destinationArray[5];
std::copy(std::begin(sourceArray), std::end(sourceArray), std::begin(destinationArray));
// 打印目标数组中的内容
for (int i = 0; i < 5; ++i) {
std::cout << destinationArray[i] << " ";
}
return 0;
}
使用 std::memcpy 函数:
#include <cstring>
#include <iostream>
int main() {
int sourceArray[] = {1, 2, 3, 4, 5};
int destinationArray[5];
std::memcpy(destinationArray, sourceArray, sizeof(sourceArray));
// 打印目标数组中的内容
for (int i = 0; i < 5; ++i) {
std::cout << destinationArray[i] << " ";
}
return 0;
}
这两种方法都可以用来拷贝数组,您可以根据自己的需求选择适合的方法。
原文地址: https://www.cveoy.top/t/topic/cvep 著作权归作者所有。请勿转载和采集!