Vector Base Notes

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.