"C + + foundation 04" Vector detailed explanation

Source: Internet
Author: User

According to the beginning of writing a blog There are always some things habits, add chicken soup, today please forgive me remember.

=============================================


The content to be written today is a sequential container. First, the standard library defines three sequential container types: Vector,list and Deque (double-ended queues), which describes the vector container.

The first thing to know. a vector is not a data type, but a class template that can be used to define arbitrary types of data. Let's say vector<int> is a data type. Vector<string> is also a data type. we need to include the header file before using vectors.

#include <vector>using std::vector;

1.vector initialization

Vector<t> v1;       Initializes an empty vectorvector<t> v2 (v1);   V2 is a copy of V1 vector<t> v3 (n,i);  N a vectorvector<t> v4 (n) with a value of I;    V4 a vector with n default initialization values, such as int default 0. String Default "")

2. iterators

Each standard library container type defines a member named iterator. That is, iterators. The type that the iterator points to is the type that is actually stored in the vector container, for example

Vector<int>iterator ITER;
iterators are often used to traverse containers. The most common is the begin and end operations, Vector.begin () returns the first element in the vector, and vector.end () returns the next End element.

vector<int> ivec;for (int i = 0; I <=; i++)  ivec.push_back (i); for (vector<int>::iterator iter = Ivec. Begin (); Iter! = Ivec.end (); ++iter) {  *iter = 0;   Traverse vector, change the value to 0}
It is important to note that if an element is added or deleted, the iterator is invalidated and the value of the iterator needs to be adjusted. Otherwise, it is very likely to cause a crash at execution time. Point is very important.

3.vector of regular use operation

join: It is important to note that adding a new element may invalidate the iterator, so the program needs to ensure that the iterator can be updated after the insert or push operation.

add element V.push_back (t);               Add an element Tv.insert (iter,t) at the tail of the vector;            Inserts an element t before the element pointed to by the iterator ITER, and returns the iterator V.insert (iter,n,t) of the newly added element;          Inserts n elements t in front of the element pointed to by the iterator Iter, returning Voidv.insert (Iter,iter1,iter2);  Inserts an element between the iterator [Iter1,iter2] in front of the element pointed to by the iterator ITER (left closed right). return void

All container types support relational operators that are relatively large, and the rules are:

V1 and v2 are equal in length and all elements. Then v1=v2, otherwise unequal.

V1 length is less than V2, but v1 all elements and v2 are equal, V1 < v2. V1 and V2 elements, the result depends on the first unequal element.

Vector-sized operations:

V.size ();      Returns the number of elements in V, returns the type V::size_typev.max_size ();  Return v can hold the maximum number of elements v.empty ();     Inferred whether it is an empty v.resize (n);   Adjusts the length of the V so that it can hold n elements. Assuming N<v.size (), delete the extra element, or join the element v.resize (n,t) that is initialized with the value; Adjust the length of V so that it can hold n elements, all newly added element values are T

Vector interview:

V.back ();   Returns a reference to the last element of V V.front ();  Returns a reference to the first element of V V[n];       Returns a reference to V subscript n V.at[n];    Returns a reference to a V subscript N//Returns a reference, note and an iterator that returns a pointer to the vector<int> v;//iterator vector<int>::iterator iter = V.begin ();//reference , the following val = val2vector<int>::reference val = V.front (); Vector<int>::reference val2 = *v.begin ();
Vector delete operation:

V.erase (ITER);        Remove the element that ITER points to and return to the next element of Iter V.erase (ITER1,ITER2); Delete [Iter1,iter2] between the elements (left closed right open) v.clear ();            All deleted and returned to Voidv.pop_back ();         Delete the last one. return void

Assignment Operation:

V1 = v2;                Copy v2 to V1v1.swap (v2);            Swap content: Exchange elements between V1 and V2, faster than v2 copy to V1 v1.assign (ITER1,ITER2); Set again: Copy the element between [Iter1,iter2] (left closed right) to V V1.assign (n,t);         Set again: Set V again to n an element with a value of t
Note that swap does not invalidate the iterator.

Assign will remove all elements of the vector and then insert the new element. assing can be used for: in the same or different container, the element type is different but mutually compatible conversion assignment. (for example, the assignment between Vector<char*> and list<string>)

vector<char*> v1;for (int i = 0; I <=; i++)  v1.push_back ("dddd");list<string> list1;list1.assign ( V1.begin (), B1.end ());

4.vector Container Self-growth

The first thing to make clear is that the elements of the vector container are stored in memory in a continuous manner.

Think about the assumption that when new elements are added, there is no room to accommodate the new elements, and you can't just find a place to put new elements. so you need to allocate the vector's storage space again:copy the old element to the new storage space. Inserts a new element. Delete old storage space.

Let's say that the vector is doing this one every time a new element is added , What is the efficiency? so. It is obvious that vector design also takes this into consideration, and the memory allocation strategy used by authors is to store elements continuously at minimal cost.

In terms of popular big plain English, it is every time the allocation will be more than you currently need more space, when the allocated space has been used to open up new space.

First look at the capacity and reserve operations :

V.size ();     Returns the number of elements in the vector v.capacity (); Returns the total number of elements that a vector can store v.reserve (n); Manually set the vector container to reserve n elements of space
give a simple example to illustrate the relationship between them:

vector<int> v;cout<< "vector size:" <<v.size () <<endl;        Output 0cout<< "vector capacity:" <<v.capacity () <<endl;//output 0//add 24 elements for (int i = 0; I < 24; i++)  v.push_back (i);cout<< "vector size:" <<v.size () <<endl;        Output 24cout<< "vector capacity:" <<v.capacity () <<endl;//output 32
it's clear. capacity are always greater than or equal to size. As for why is 32? because each time the vector has to allocate new storage space, it is allocated again with the allocation policy of doubling the current capacity. For example, you add a 1 element. Size for 1,capacity is also 1, then join again, capacity multiply by 2, and then join again by 2. For example, the following:

At the time of accession size and capacity relationship://v.size ()--v.capacity ()        0  -  0        1  -  1        2  -  2        3  -  4        4  -  4        5  -  8        9  -        ... etc...
or we can set our own reservation, change the example above:

Vector<int> V;v.reserve (;cout<<) "Vector size:" <<v.size () <<endl;        Output 0cout<< "vector capacity:" <<v.capacity () <<endl;//output 50//add 50 elements for (int i = 0; I < 50; i++)  v.push_back (i);//Add a V.push_back (Wuyi);cout<< "vector size:" <<v.size () <<endl;        Output 51cout<< "vector capacity:" <<v.capacity () <<endl;//output 100

5. Advantages and disadvantages of containers:

vector: Advantages: High-speed random interview .

Cons: inserting or deleting at any location in the container is more expensive than inserting or deleting at the end of the container.

list: is a discontinuous storage, the advantage: in the container wherever the efficient insertion and deletion of elements.

Cons: Random access is not supported. The access element needs to traverse other elements.

DEUQE: has more complex data structures. Pros: Both inserts and deletes at both ends of the device are very fast and support efficient random access. Disadvantage: Insertion or deletion is very inefficient in the middle.

6. Infer which type of container to choose:

(1) If you need an efficient random access element, use a vector or deque.

(2) You need to efficiently insert or delete elements in the middle of the container, use list.

(3) If it is not inserted in the middle position, but the container header or tail insert, then use Deque.

(4) If you need both efficient random access and efficient intermediate insertion, you can add elements to the list and then sort what. And then copied into the vector.


=========================================


If you don't sleep, you'll die.


Reprint Please specify source: http://blog.csdn.net/shun_fzll/article/details/37917133


Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

"C + + foundation 04" Vector detailed explanation

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.