std::"copy
时间: 2023-08-27 12:04:29 浏览: 61
std::copy是C++标准库中的一个函数,用于将一个序列的元素复制到另一个序列中。它接受三个参数:源序列的起始位置、源序列的结束位置和目标序列的起始位置。[1]在使用std::copy函数时,需要确保目标序列有足够的空间来存储源序列的元素,否则会导致崩溃。为了避免这种情况,可以使用std::back_inserter来动态地向目标序列中插入元素,而不需要提前分配足够的空间。[1]
例如,如果想将一个数组arr中的元素复制到一个新的数组newArr中,并保留newArr中已有的元素,可以使用std::copy函数和std::back_inserter,如下所示:[2]
```cpp
#include <iostream>
#include <iterator>
#include <algorithm>
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int newArr[12] = {11, 12, 0};
std::copy(std::begin(arr), std::end(arr), std::back_inserter(newArr));
for (int i = 0; i < 12; ++i) {
std::cout << newArr[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
这段代码将arr数组中的元素复制到newArr数组中,并保留newArr中已有的元素。输出结果为:11 12 1 2 3 4 5 6 7 8 9 10。
另外,如果想将一个数组arr中的元素复制到一个新的数组newArr中,并覆盖newArr中的元素,可以直接使用std::copy函数,如下所示:[3]
```cpp
#include <iostream>
#include <algorithm>
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int newArr[12] = {0};
std::copy(std::begin(arr), std::end(arr), std::begin(newArr));
for (int i = 0; i < 12; ++i) {
std::cout << newArr[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
这段代码将arr数组中的元素复制到newArr数组中,并覆盖newArr中的元素。输出结果为:1 2 3 4 5 6 7 8 9 10 0 0。