如何在 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