The 20th question of C/C + + STL (second) vector of "College recruit Interview"

Source: Internet
Author: User

1. Dynamic growth of vectors

When adding elements, if the vector space is not large enough, it will be twice times the original size of another large new space, and then copy the original space content , add elements at the end of the new space, and release the original space . Vector space dynamic increase in size, not in the original space after the adjacent address to add new space, because the vector space is continuously distributed linearly , can not guarantee the space after the original space can be configured. Therefore, any action on the vector, once the space is reconfigured, will invalidate all iterators that point to the original vector .

Vector size (), capacity (), reserve (), resize () function:

The memory layout of the vector object is as follows:

The start iterator points to the first element of the used space, and finish points to the next position of the trailing element of the used space, end_of_storage points to the end of the free space. The size () function returns the amount of space used, capacity () returns the total space size, and Capacity ()-size () is the remaining free space.     When size () and capacity () are equal, the vector's current space is exhausted, and if a new element is added, it will cause the dynamic growth of the vector space. Because dynamic growth causes the reallocation of memory space, copying of the original space, and releasing the original space, these processes can reduce program efficiency. Therefore, you can use Reserve (n) to pre-allocate a larger size of memory space, so that when the specified size of memory space is not used, the memory space will not be re-allocated, which increases efficiency.    The call to reserve (n) changes the vector capacity only when n>capacity () is called. The resize () member function only changes the number of elements and does not change the vector's capacity. Program Description:Allocated two containers, a, B. Each adds 1 elements to a, adding 10 times. Use reserve () to allocate a space of 10 elements in advance for B, then add 1 elements to B each time, adding 10 times. When the B space is full, add 1 elements to it. Then use reserve () for B to allocate a 15 (smaller than the original space) element size space.    Then use resize () to change the number of elements in B to 5. Observe the changes in size () and capacity () in the above process.
#include <iostream> #include <vector>using namespace Std;int main () {vector<int> A;    cout << "A.size ():" << a.size () << "a.capacity ():" << a.capacity () << Endl;        for (int i = 0; i < i++) {a.push_back (i);    cout << "A.size ():" << a.size () << "a.capacity ():" << a.capacity () << Endl;    } cout << Endl;    Vector<int> b;    B.reserve (10);        for (int i = 0; i < i++) {b.push_back (i);    cout << "B.size ():" << b.size () << "b.capacity ():" << b.capacity () << Endl;    } b.push_back (11);    cout << "B.size ():" << b.size () << "b.capacity ():" << b.capacity () << Endl;    cout << Endl;    B.reserve (15);    cout << "After B.reserve": "<< Endl; cout << "B.size ():" << b.size () << "b.capacity ():" << b.capacity () << Endl;    B.resize (5);    cout << "After B.resize (5):" << Endl;    cout << "B.size ():" << b.size () << "b.capacity ():" << b.capacity () << Endl; return 0;}
Output:
A.size ():0A.capacity ():0a.size ():1A.capacity ():1a.size ():2A.capacity ():2a.size ():3A.capacity ():4a.size ():4A.capacity ():4a.size ():5A.capacity ():8a.size ():6A.capacity ():8a.size ():7A.capacity ():8a.size ():8A.capacity ():8a.size ():9A.capacity (): -a.size ():TenA.capacity (): -b.size ():1B.capacity ():Tenb.size ():2B.capacity ():Tenb.size ():3B.capacity ():Tenb.size ():4B.capacity ():Tenb.size ():5B.capacity ():Tenb.size ():6B.capacity ():Tenb.size ():7B.capacity ():Tenb.size ():8B.capacity ():Tenb.size ():9B.capacity ():Tenb.size ():TenB.capacity ():Tenb.size (): OneB.capacity (): -After B.reserve ( the): B.size (): OneB.capacity (): -After b.resize (5): B.size ():5B.capacity (): -
Phenomenon:A re-allocates space of 5 times, each time is twice times the previous space. B is not redistributed when the reserve () is not pre-allocated space. Conclusion:1. Empty vector objects, size () and capacity () are 0 2.When the space size is insufficient, the newly allocated space is twice times the size of the original space。 3. Use reserve () to pre-allocate a piece of memory, no redistribution is caused when space is not full, resulting in increased efficiency。 4.when reserve () allocates more space than the original space, it does not cause redistribution。 5.the Resize () function only changes the number of elements in the container, without changing the container size (capacity ())。

2. Use of vectors

(1) header file

#include <vector>

(2) Declaration and initialization

Vector<int> Vec;        declares an int type vector vector<int> VEC (5);     declares an int vector with an initial size of 5 vector<int> VEC (10, 1); Declares a vector vector<int> VEC (TMP) with an initial size of 10 and a value of 1;   Declare and initialize the VEC vector vector<int> tmp (Vec.begin (), Vec.begin () + 3) with the TMP vector;  Initialized with the No. 0 to 2nd value of the vector vec tmpint arr[5] = {1, 2, 3, 4, 5};   Vector<int> Vec (arr, arr + 5);      The elements of the ARR array are used to initialize the VEC vector//Description: Of course not including the arr[4] element, and the end pointer refers to the next element of the end element,//This is primarily intended to be unified with the Vec.end () pointer. Vector<int> VEC (&arr[1], &arr[4]); ARR[1]~ARR[4] in the range of elements as the initial value of the VEC

(3) Basic operation

1?? Capacity

    • Vector size: vec.size ();
    • Vector Maximum Capacity: vec.max_size ();
    • Change vector size: vec.resize ();
    • Vector true Size: vec.capacity ();
    • Vector empty: Vec.empty ();
    • Reduce the size of the vector to meet the size of the storage space occupied by the element: Vec.shrink_to_fit (); Shrink_to_fit

2?? Modify

    • Multiple element Assignment: Vec.assign (); Array-like assignment similar to initialization
    • add element at the end: Vec.push_back ();
    • Delete element at end: Vec.pop_back ();
    • Insert element Anywhere: Vec.insert ();
    • Delete elements Anywhere: vec.erase ();
    • Swaps the elements of two vectors: Vec.swap ();
    • Empty vector elements: vec.clear ();

3?? Iterators

    • Start pointer: Vec.begin ();
    • End pointer: Vec.end (); Point to the next position of the last element
    • Start pointer to constant: Vec.cbegin (); This means that you cannot modify what you refer to by this pointer, but you can still modify it in other ways, and the pointer is movable.
    • Pointer to the end of the constant: Vec.cend ();

4?? Access to elements

    • Subscript access: vec[1]; Does not check if it is out of bounds
      • At Method Access: vec.at (1); //The difference between the two is that the at will check if it is out of bounds, is thrown out of the range exception
    • Access the first element: Vec.front ();
    • Access the last element: Vec.back ();
    • Returns a pointer: int* p = vec.data (); The reason for this is that the vector is an array of contiguous storage in memory, so you can return a pointer to the array. This is a c++11 feature.

5?? Algorithm

Traverse

Vector<int>::iterator it;for (it = Vec.begin (); It! = Vec.end (); it++)    cout << *it << endl;//or for ( size_t i = 0; I < vec.size (); i++) {    cout << vec.at (i) << Endl;}

The 20th question of C/C + + STL (second) vector of "College recruit Interview"

Related Article

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.