如何在 C++ 中复制数组
本文将介绍如何在 C++ 中复制一个数组。
使用 copy()
函数在 C++ 中复制一个数组
copy()
方法是用一个函数调用复制基于范围的结构的推荐方法。copy()
取范围的第一个和最后一个元素以及目标数组的开始。注意,如果第三个参数在源范围内,你可能会得到未定义的行为。
#include <iostream>
#include <vector>
#include <iterator>
#include <string>
using std::cout; using std::endl;
using std::vector; using std::copy;
using std::string;
int main() {
vector<string> str_vec = { "Warty", "Hoary",
"Breezy", "Dapper",
"Edgy", "Feisty" };
vector<string> new_vec(str_vec.size());
copy(str_vec.begin(), str_vec.end(), new_vec.begin());
cout << "new_vec - | ";
copy(new_vec.begin(), new_vec.end(),
std::ostream_iterator<string>(cout," | "));
cout << endl;
return EXIT_SUCCESS;
}
输出:
new_vec - | Warty | Hoary | Breezy | Dapper | Edgy | Feisty |
使用 copy_backward()
函数复制一个数组
copy_backward()
方法可以将一个数组与原始元素的顺序反过来复制,但顺序是保留的。当复制重叠的范围时,在使用 std::copy
和 std::copy_backward
方法时应牢记一点:copy
适合于向左复制(目标范围的开始在源范围之外)。相反,copy_backward
适合于向右复制(目标范围的末端在源范围之外)。
#include <iostream>
#include <vector>
#include <iterator>
#include <string>
using std::cout;
using std::endl;
using std::vector;
using std::copy_backward;
using std::string;
int main() {
vector<string> str_vec = { "Warty", "Hoary",
"Breezy", "Dapper",
"Edgy", "Feisty" };
vector<string> new_vec(str_vec.size());
copy_backward(str_vec.begin(), str_vec.end(), new_vec.end());
cout << "new_vec - | ";
copy(new_vec.begin(), new_vec.end(),
std::ostream_iterator<string>(cout," | "));
cout << endl;
return EXIT_SUCCESS;
}
使用 assign()
方法复制数组
assign()
是 vector
容器的内置方法,它用传递的范围元素替换调用的 vector
对象的内容。assign()
方法可以在复制类型的向量时很方便,因为这些向量可以很容易地相互转换。在下面的代码示例中,我们演示了通过一个 assign()
调用将一个字符向量复制到整型向量中的方法。
#include <iostream>
#include <vector>
#include <iterator>
#include <string>
using std::cout;
using std::endl;
using std::vector;
int main() {
vector<char> char_vec { 'a', 'b', 'c', 'd', 'e'};
vector<int> new_vec(char_vec.size());
new_vec.assign(char_vec.begin(), char_vec.end());
cout << "new_vec - | ";
copy(new_vec.begin(), new_vec.end(),
std::ostream_iterator<int>(cout," | "));
cout << endl;
return EXIT_SUCCESS;
}
输出:
new_vec - | 97 | 98 | 99 | 100 | 101 |
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn