The vector object replicates part of the object.
Vector<int> Arr1{1, 2, 3, 4, 5, 6};
1. Vector<int> arr2 (Arr1.begin (), Arr1.begin () +4);
2. vector<int> arr2;
Copy (Arr1.begin (), Arr1.begin () +4, Arr2.begin ());
PS: Note that the interval of replication is [), left-right open. So all of the above are copied only to {1,2,3,4}
The parameters of the vector's constructor are both iterators, if the original array pointers are also possible.
The copy parameter defaults to the iterator.
#include <iostream>
#include <vector>
using namespace std;
int main (void)
{
vector<int> arr2;
int arr3[3] = {1,2,3};
Arr2.resize (3);
Std::copy (ARR3, Arr3+2,arr2.begin ());
for (auto x:arr2)
cout << x << ';
cout<< Endl;
return 0;
}
This is a special example ARR2 does not have a pre allocation size, run a direct report segment error.
g++ (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0 g++ version
Allocate the memory before running copy. Resize () and reserve ()
This is resize () to reassign the container size and initialize the object.
In fact, you can also pass the vector's length in the constructor and initialize the object.
Here, with the reserve () function, there is no effect, the function of the reserve function is to allocate the memory of N int objects.
The reserve does not initialize the object. So the vector object that invokes the reserve function only calls copy to copy the data to the
Vector memory, which can cause replication to fail.
The reserve is indeed able to reduce the cost of other costs of repeated requests for increased memory data movement as the vector continues to increase. releasing the memory occupied by the vector
The Clear,erase function destroys the object, but does not release the memory occupied by the vector.
C++11 provides a function to release vector memory Shrink_to_fit ()
Swap swap is also available.
1. Vector (ARR2). Swap (ARR2);//Effect and shrink_to_fit () function
2. Vector (). Swap (ARR2);//To release all memory and data.