In case of arrays, there is no much choice to copy an array into other, other than iterative method i.e running a loop to copy each element at respective index. But Vector classes has more than one methods to copy entire vector into other in easier ways.There are basically two types of copying :- 在数组方面,复制一个数组到另个里面没有多少方法可以选择,除了循环的方法,比如运行一个循环把每个元素复制到另一个。但是vector有更多的方法。
1 Method 1 : Iterative method.
This method is a general method to copy, in this method a loop is used to push_back() the old vector elements into new vector.They are deeply copied 这是通常的方法--复制,使用loop。
// C++ code to demonstrate copy of vector
// by iterative method.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
// Initializing vector with values
vector<int> vect1{1, 2, 3, 4};
// Declaring new vector
vector<int> vect2;
// A loop to copy elements of
// old vector into new vector
// by Iterative method
for (int i=0; i<vect1.size(); i++)
vect2.push_back(vect1[i]);
cout << "Old vector elements are : ";
for (int i=0; i<vect1.size(); i++)
cout << vect1[i] << " ";
cout << endl;
cout << "New vector elements are : ";
for (int i=0; i<vect2.size(); i++)
cout << vect2[i] << " ";
cout<< endl;
// Changing value of vector to show that a new
// copy is created.
vect1[0] = 2;
cout << "The first element of old vector is :";
cout << vect1[0] << endl;
cout << "The first element of new vector is :";
cout << vect2[0] <<endl;
return 0;
}
Output:
Old vector elements are : 1 2 3 4
New vector elements are : 1 2 3 4
The first element of old vector is : 2
The first element of new vector is : 1
In the above code, on changing the value at one vector did not alter value at other vector, hence they are not allocated at same address, hence deep copy. 这种情况下,一个vector的值改变,另一个vector的值不会改变,所以他们分配的地址空间不同,是深度复制。