A brief introduction to vectors (vector containers) in C + + STL

Source: Internet
Author: User

Original: http://www.seacha.com/article.php/knowledge/cbase/2013/0903/2205.html

C + + vector (vector container) is a linear sequential structure. Equivalent to an array, but its size can be unspecified and automatically expanded. It can be manipulated like an array, because of its nature we can view vectors as dynamic arrays, or as dynamic memory. After creating a vector, it automatically allocates a contiguous memory space in memory for data storage, the initial space size can be specified beforehand or by the vector by default, this size is the return value of the capacity () function. The vector allocates a chunk of memory when the stored data exceeds the allocated space, but the allocation is time-consuming, and it does this when reallocating space: first, the vector will request a larger chunk of memory, and then the original data will be copied into the new memory block; Destroy the object in the original memory block (call the destructor of the object); Finally, the original memory space is freed. If the amount of data the vector is holding is large, such an operation will certainly result in poor performance (which is why the vector is designed to be a more easily copied value type). So vector is not under what circumstances performance is good, only in advance to know its size, the performance of the vector is optimal.features of vector:  (1) specifies a block of contiguous storage as an array, but the space can be dynamically extended. That is, it can operate like an array, and it can be manipulated dynamically. Usually manifested in push_back () Pop_back (). (2) Random access, it is accessed like an array, that is, the support [] operator and vector.at () (3) To save space, because it is continuous storage, in the area where the data is stored is not wasted, but to make it clear that a little vector is not a full deposit in most cases, In an area that is not stored, it is actually wasteful. (4) In the internal insert, delete operation is very inefficient, such operations are basically forbidden. Vectors are designed to append and delete operations on the backend only because the implementation of the vector is based on the principle of the sequential table. (5) Push and pop can only be carried at the end of the vector, not on the head of the vector. (6) When the dynamically added data exceeds the size assigned by the vector, the memory is redistributed, copied and released, which consumes performance. Therefore, to achieve the optimal performance of vectors, it is best to specify the space size when the vector is created. The  vectors contains a series of continuously stored elements that behave in a similar array. Accessing any element in the vector, or adding elements from the end, can be done in constant-level time complexity, while the element looking for a particular value or inserting an element into the vector is a linear time complexity.  1.constructors Constructors  vector<int> v1; Constructs an empty vectorvector<int> v1 (5, 42); Constructs a vector 2.operators that contains 5 elements with a value of 42 to assign or compare vectors  c++ vectors can use the standard operators: = =,! =, <=, >=, <, and > . To access an element in a particular position in a vector you can use the [] operator .  Two vectors are considered equal if:  1. They have the same capacity   2. All elements of the same location are equal .  The comparison between the sizes of vectors is in accordance with the rules of the dictionary.  3.assign () to the vector element assignment   syntax:  //assigns the element of the interval [start, end] to the current vectorvoid assign ( Input_iterator start, Input_iterator end);//assigns NUM values to the Val element into the vector, this function will clear out the previous contents of the vector assigned value. void assign (Size_type num, const type &val),   4.at () returns the element   syntax at the specified location:  type at (Size_type Loc);//Poor More equal to V[i];  5.back () returns the last element  6.begin () returns the iterator  7.capacity () of the first element and returns the number of elements that the vector can hold ( Without reallocating memory)  8.clear () empties all elements  9.empty () to determine if the vector is empty (null when returning True)  10.end () returns an iterator to the last element: The next position of the last Element)  11.erase () deletes the specified element   syntax:  iterator erase (Iterator loc);//delete the element at Loc iterator Erase ( Iterator start, iterator end);//delete the element between start and end  12.front () returns a reference to the first element  13.get_allocator () returns the vector's memory allocator  14.insert () insert element into vector   syntax:  //inserts an element with a Val value at the specified location, and returns an iterator to the element iterator insert (iterator loc, const TYPE &val);//Insert the num value val element void Insert (iterator loc, size_type num, const type &val) before Loc at the specified position,//insert interval before loc at the specified position [ All elements of start, end] void insert (Iterator loc, input_iterator start, Input_iterator end);  15.max_size () Returns the most of the elements that the vector can hold.Large quantity (upper limit)  16.pop_back () removes the last element  17.push_back () adds an element at the end of the vector  18.rbegin () returns the inverse iterator  19 of the tail of the vector. Rend () returns the inverse iterator of the vector start  20.reserve () sets the minimum element capacity of the vector  //the space for the current vector to hold at least a total of size elements  21.resize () Change the size   syntax of vector elements:  //Changes the size of the current vector to sizes, and assigns a value valvoid resize (size_type size, type val) to the newly created element;  22. Size () returns the number of vector elements  23.swap () Exchange two vector  syntax:  void swap (vector &from);  Vector usage:1. Disclaimer:A vector is similar to a dynamic one-dimensional array. Vector<int> A; Declares an element to be of type int vector avectot<mytype> A; Declares an element of vector a of type MyType here A contains 0 elements, the value of both a.size () is 0, but it is dynamic and its size changes as the data is inserted and deleted. Vector<int> A (100, 0); Here is an integer vector that has been stored for 100 0. You can declare a vector object in the following ways: Vector<float> V (5, 3.25); The initialization has 5 elements whose values are 3.25vector<float> v_new1 (v);vector<float> v_new2 = v;vector<float> v_new3 (V.begin ( ), V.end ()); These four vector objects are equal and can be judged by operator==.2. Vector manipulationCommon functions: size_t size (); Returns the size of the vector, that is, the number of elements contained in void Pop_back (); Remove the element at the end of the vector, the vector size minus one void push_back (); Used to add the element T back at the end of the vector (); Returns the element at the end of the vector void Clear (); The vector is emptied and the vector size becomes 0 other access methods: cout<<a[5]<<endl;cout<<a.at (5) <<endl; The difference is that the latter throws an exception when the access is out of bounds, while the former does not. 3. Traversal   (1). For (Vector<datatype>::iterator It=a.begin (); It!=a.end (); it++) cout<<*it<<endl;  (2). for (int i=0;i<a.size;i++) cout<<a[i]<<endl;  now wants the maximum number of elements that can be saved in a container by using the member function of the Vector class Max_size ():  vector<shape>::size_type max_size = my_shapes.max_size ();  The actual size of the current container---the existing number of elements in size ():  Vector<shape>::size_type size = My_shapes.size ();  is like Size_type describes the type of vector size, value_type describes the type of object that is saved:  cout << "value type:" << typeid (Vector<float>::value_type). Name ();  output:  value type: float  can use capacity () to get the number of allocated memory elements in the vector: vector<int> v;vector<int>::size_type capacity = V.capacity ();  vector is similar to an array, you can use subscript [] to access:vector<int> V, v[0] = 101;  Notice that there is a pre-allocated space for 10 elements. You can also use the Insert function provided by the vector to dynamically extend the container. The member function push_back () adds an element to the tail of the vector:  v.push_back (3);  can also perform the same work with the Insert () function:  v.insert (V.end (), 3);   Here the Insert () member function requires two parameters: an iterator to the specified position in the container (iterator), an element to be inserted   into. Insert() inserts an element into the iterator before the specified element.   Now makes a point of interpreting iterators (Iterator). Iterator is a generalization of the pointer (pointer), Iterator requires the definition of  operator*, which returns the value of the specified type. Iterator are often associated with containers. Example: vector<int> V (3); v[0] = 5;v[1] = 2;v[2] = 7; vector<int>::iterator first = V.begin (); vector <int>::iterator last = V.end (), while (first! = last)     cout << *first++ << "";  the output of the above code is :  5 2 7 begin () returns the iterator of the first element in the vector, and end () returns not the  iterator of the last element, but the past. Called Past-the-end iterator in the STL.  4. Use as dynamic memoryvector<unsigned char> vecdata;vecdata.resize (+) unsigned char *data = (unsigned char *) &_vecData[0]; if (<= Datalen + new_datalen) {Vecdata.reserve (datalen + new_datalen);//or add a specified size of data. }vecdata.insert (_vecdata.end (), (unsigned char) buf[0], RC); cout << "Data:" << data << Endl; (Editor: admin)



A brief introduction to vectors (vector containers) in C + + STL

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.