In C++, you can copy a vector by using the copy constructor or by using the assignment operator.
In this example,
originalVector
with some values.copiedVector
.originalVector
will not affect copiedVector
.#include <iostream>
#include <vector>
int main() {
std::vector<int> originalVector = {1, 2, 3, 4, 5};
std::vector<int> copiedVector(originalVector);
std::cout << "Original vector: ";
for (int num : originalVector) {
std::cout << num << " ";
}
std::cout << "\n";
std::cout << "Copied vector: ";
for (int num : copiedVector) {
std::cout << num << " ";
}
std::cout << "\n";
return 0;
}
Original vector: 1 2 3 4 5 Copied vector: 1 2 3 4 5
In this example,
originalVector
with some values.originalVector
to copiedVector
using the assignment operator (=
).originalVector
will not affect copiedVector
.#include <iostream>
#include <vector>
int main() {
std::vector<int> originalVector = {1, 2, 3, 4, 5};
std::vector<int> copiedVector = originalVector;
std::cout << "Original vector: ";
for (int num : originalVector) {
std::cout << num << " ";
}
std::cout << "\n";
std::cout << "Copied vector: ";
for (int num : copiedVector) {
std::cout << num << " ";
}
std::cout << "\n";
return 0;
}
Original vector: 1 2 3 4 5 Copied vector: 1 2 3 4 5
In this tutorial, we learned How to Copy a Vector in C++ language with well detailed examples.