STL 2: usage of vector containers

Source: Internet
Author: User
Document directory
  • 2. Example of adding and obtaining elements:
  • 3. Element modification example
  • 4. Example of deleting a vector

A vector class is called a Vector class. It implements a dynamic array and is used as an array of objects with variable element quantity. Like an array, the vector class uses subscript starting from 0 to represent the position of an element. However, unlike an array, when a vector object is created, the number of elements in the array automatically changes as the number of elements in the vector object increases or decreases.

Common functions of the Vector class are as follows:

1. Constructor
  • Vector (): creates an empty vector.
  • Vector (INT nsize): Creates a vector with the number of elements being nsize.
  • Vector (INT nsize, const T & T): Creates a vector. The number of elements is nsize and the value is T.
  • Vector (const vector &): copy constructor
  • Vector (begin, end): Copies the elements of another array in the [begin, end) range to the vector.
2. Add a function

  • Void push_back (const T & X): adds an element X to the end of the vector.
  • Iterator insert (iterator it, const T & X): Add an element x before the iterator points to the element in the vector.
  • Iterator insert (iterator it, int N, const T & X): Add n identical elements before the iterator points to an element in the vector x
  • Iterator insert (iterator it, const_iterator first, const_iterator last): In a vector, the iterator inserts data between [first, last) of another vector of the same type before the element.
3. delete a function

  • Iterator erase (iterator it): deletes the iterator pointing to an element in the vector.
  • Iterator erase (iterator first, iterator last): deletes elements in the [first, last) vector.
  • Void pop_back (): deletes the last element in the vector.
  • Void clear (): clears all elements in a vector.
4. traversal Functions

  • Reference at (int pos): returns the reference of the POs position element.
  • Reference Front (): returns the reference of the first element.
  • Reference back (): returns the reference of the last element.
  • Iterator begin (): returns the vector header pointer pointing to the first element.
  • Iterator end (): returns the vector tail pointer pointing to the next position of the last element of the vector.
  • Reverse_iterator rbegin (): reverse iterator pointing to the last element
  • Reverse_iterator rend (): reverse iterator pointing to the position before the first element
5. Judgment Functions

  • Bool empty () const: determines whether the vector is empty. If it is empty, there is no element in the vector.
6. Size Functions

  • Int size () const: returns the number of elements in the vector.
  • Int capacity () const: returns the maximum element value that the current vector zhanghong can hold.
  • Int max_size () const: returns the maximum number of allowed vector elements.
7. Other functions

  • Void swap (vector &): Exchange data of two vectors of the same type
  • Void assign (int n, const T & X): set the value of the nth element in the vector to X
  • Void assign (const_iterator first, const_iterator last): the element in the [first, last) vector is set to the current vector element.
Example: 1. Initialization example
# Include "stdafx. H "# include <iostream >#include <vector> using namespace STD; Class A {// empty class}; int _ tmain (INT argc, _ tchar * argv []) {// int-type vectorvector <int> vecint; // float-type vectorvector <float> vecfloat; // custom type, save vectorvector <A> Veca; // custom type. Save vectorvector <A *> vecpointa; return 0;} pointing to the pointer of Class ;}

// Vectorsample. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream >#include <vector> using namespace STD; Class A {// empty class}; int _ tmain (INT argc, _ tchar * argv []) {// int-type vector, which contains three elements: vector <int> vecinta (3); // int-type vector, contains 3 elements and each element is 9 vector <int> vecintb (); // copy vecintb to vecintcvector <int> vecintc (vecintb); int iarray [] = {2, 4, 6}; // create vecintdvector <int> vecintd (iarray, iarray + 3); // print vectora, the following code can also be used to output the data in the vector/* For (INT I = 0; I <vecinta. s Ize (); I ++) {cout <vecinta [I] <"" ;}*/cout <"vecinta:" <Endl; for (vector <int >:: iterator it = vecinta. begin (); it! = Vecinta. end (); It ++) {cout <* It <";}cout <Endl; // print vecintbcout <" vecintb: "<Endl; for (vector <int >:: iterator it = vecintb. begin (); it! = Vecintb. end (); It ++) {cout <* It <";}cout <Endl; // print vecintccout <" vecintb: "<Endl; for (vector <int >:: iterator it = vecintc. begin (); it! = Vecintc. end (); It ++) {cout <* It <";}cout <Endl; // print vecintdcout <" vecintd: "<Endl; for (vector <int >:: iterator it = vecintd. begin (); it! = Vecintd. End (); It ++) {cout <* It <"" ;}cout <Endl; return 0 ;}

The program running result is as follows:

The above Code uses four methods to create a vector and initialize it.

2. Example of adding and obtaining elements:
// Vectorsample. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream >#include <vector> using namespace STD; int _ tmain (INT argc, _ tchar * argv []) {// int type vector, contains three elements: vector <int> vecinta; // insert 1 2 3 vecinta. push_back (1); vecinta. push_back (2); vecinta. push_back (3); int nsize = vecinta. size (); cout <"vecinta:" <Endl; // print vectora. Method 1: For (INT I = 0; I <nsize; I ++) {cout <vecinta [I] <";}cout <Endl; // print vectora. Method 2: For (INT I = 0; I <nsize; I ++) {cout <vecint A. at (I) <";}cout <Endl; // print vectora, method 3: For (vector <int >:: iterator it = vecinta. begin (); it! = Vecinta. End (); It ++) {cout <* It <"" ;}cout <Endl; return 0 ;}

The code above defines an integer element Vector class, inserts three values, and outputs them in three different ways. The program runs as follows:

// Vectorsample. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream >#include <vector> using namespace STD; Class A {public: int N; public: A (int n) {This-> N = n ;}}; int _ tmain (INT argc, _ tchar * argv []) {// int vector, contains three elements: vector <A> vecclassa; A A1 (1); a A2 (2); A A3 (3); // insert 1 2 3vecclassa. push_back (A1); vecclassa. push_back (A2); vecclassa. push_back (A3); int nsize = vecclassa. size (); cout <"vecclassa:" <Endl; // print vecclassa. Method 1: For (INT I = 0; I <nsize; I ++) {Cout <vecclassa [I]. n <";}cout <Endl; // print vecclassa, Method 2: For (INT I = 0; I <nsize; I ++) {cout <vecclassa. at (I ). n <"" ;}cout <Endl; // print vecclassa. Method 3: For (vector <a >:: iterator it = vecclassa. begin (); it! = Vecclassa. End (); It ++) {cout <(* It). n <";}cout <Endl; return 0 ;}

The code above defines the element as a vector of the class, inserts three initialized classes, and outputs them in three ways. The running result is as follows:

// Vectorsample. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream >#include <vector> using namespace STD; Class A {public: int N; public: A (int n) {This-> N = n ;}}; int _ tmain (INT argc, _ tchar * argv []) {// int vector, contains three elements: vector <A *> vecclassa; A * a1 = newa (1); a * a2 = new A (2); A * a3 = new A (3 ); // insert 1 2 3vecclassa. push_back (A1); vecclassa. push_back (A2); vecclassa. push_back (A3); int nsize = vecclassa. size (); cout <"vecclassa:" <Endl; // print vecclass A, Method 1: For (INT I = 0; I <nsize; I ++) {cout <vecclassa [I]-> n <"\ t ";} cout <Endl; // print vecclassa, Method 2: For (INT I = 0; I <nsize; I ++) {cout <vecclassa. at (I)-> n <"\ t" ;}cout <Endl; // print vecclassa, method 3: For (vector <A *> :: iterator it = vecclassa. begin (); it! = Vecclassa. end (); It ++) {cout <(** it ). n <"\ t" ;}cout <Endl; Delete A1; Delete A2; Delete A3; return 0 ;}

The code above defines the element as a vector of the class pointer, inserts three initialization class pointers, and outputs the class pointed to by the pointer in three ways. The running result is as follows:

3. There are three ways to modify an element in the element example: 1. Modify the element through array, 2. Modify the element by reference, and 3. Modify the element through iterator.
// Vectorsample. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream >#include <vector> using namespace STD; int _ tmain (INT argc, _ tchar * argv []) {// int type vector, contains three elements: vector <int> vecinta; // insert 1 2 3 vecinta. push_back (1); vecinta. push_back (2); vecinta. push_back (3); int nsize = vecinta. size (); // modify vectorcout by referencing <"Modify via array, the second element is 8:" <Endl; vecinta [1] = 8; cout <"vecinta:" <Endl; // print vectorafor (vector <int>: iterator it = vecinta. begin (); it! = Vecinta. end (); It ++) {cout <* It <";}cout <Endl; // modify vectorcout by referencing <" Modify by referencing, the second element is 18: "<Endl; Int & M = vecinta. at (1); M = 18; cout <"vecinta:" <Endl; // print vectorafor (vector <int>: iterator it = vecinta. begin (); it! = Vecinta. end (); It ++) {cout <* It <";}cout <Endl; // modify vectorcout through iterator <" modified by iterator, the second element is 28 "<Endl; vector <int>: iterator itr = vecinta. begin () + 1; * itr = 28; cout <"vecinta:" <Endl; // print vectorafor (vector <int>: iterator it = vecinta. begin (); it! = Vecinta. End (); It ++) {cout <* It <"" ;}cout <Endl; return 0 ;}

The program running result is as follows: 4. The example of deleting a vector mainly uses erase and pop_back. The sample code is as follows:

// Vectorsample. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream >#include <vector> using namespace STD; int _ tmain (INT argc, _ tchar * argv []) {// int type vector, contains three elements: vector <int> vecinta; // cyclically insert 1 to 10for (INT I = 1; I <= 10; I ++) {vecinta. push_back (I);} vecinta. erase (vecinta. begin () + 4); cout <"vecinta:" <Endl; // print vectorafor (vector <int> :: iterator it = vecinta. begin (); it! = Vecinta. end (); It ++) {cout <* It <"\ t" ;}cout <Endl; // Delete the 2-5 element vecinta. erase (vecinta. begin () + 1, vecinta. begin () + 5); cout <"delete vecinta after elements 2-5:" <Endl; // print vectorafor (vector <int> :: iterator it = vecinta. begin (); it! = Vecinta. end (); It ++) {cout <* It <"\ t" ;}cout <Endl; // Delete the last element vecinta. pop_back (); cout <"vecinta after deleting the last element:" <Endl; // print vectorafor (vector <int>: iterator it = vecinta. begin (); it! = Vecinta. End (); It ++) {cout <* It <"\ t" ;}cout <Endl; return 0 ;}

The program running result is as follows: 3. further understanding of vector, as shown in: when the Code vector <int> V () is executed, two integer Element Spaces are created in the memory. The value is 5. when an element is added, the original space consists of two programming and four integer Element Spaces, and element 1 is put into 3rd integer spaces, and 4th space is reserved. When element 2 is added, the value 2 is directly put into 4th spaces. When element 3 is added, because there is no reserved space in the original vector, the memory space is changed from 4 to 8 Integer spaces, and the value is placed into 5th Memory Spaces. In short, when the new element is expanded, if the current capacity is exceeded, the capacity will be automatically expanded by 2 times. If the capacity is still insufficient by 2 times, it will continue to expand by 2 times. This figure shows how to add a new space directly based on the original space. In fact, it is much more complicated, including reconfiguration, element movement, and the process of releasing the original space. Therefore, when a new element is added to a vector container, it may be completed quickly (directly in the reserved space), and it may be a little slow (add new elements after resizing ); it is faster to modify the element value. for deleting an element, it is faster to delete the tail element, and the non-tail element is slower, because it involves moving the deleted element. 4. Example

// Vectorsample. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream> # include <vector> # include <string> using namespace STD; class student {public: String m_strno; string m_strname; string m_strsex; string m_strdate; public: student (string strno, string strname, string strsex, string strdate) {m_strno = strno; m_strname = strname; m_strsex = strsex; m_strdate = strdate;} void display () {cout <m_strno <"\ t"; cout <m_strname <"\ t"; cout <m_strsex <"\ t "; cout <m_strdate <"\ t" ;}}; class studcollect {vector <student> m_vstud; public: void add (student & S) {m_vstud.push_back (s );} student * Find (string strno) {bool bfind = false; int I; for (I = 0; I <m_vstud.size (); I ++) {student & s = m_vstud.at (I); If (S. m_strno = strno) {bfind = true; break ;}} student * s = NULL; If (bfind) S = & m_vstud.at (I); Return s ;}}; int _ tmain (INT argc, _ tchar * argv []) {student S1 ("1001", "zhangsan", "boy", "1988-10-10 "); student S2 ("1002", "Lisi", "boy", "1988-8-25"); Student S3 ("1003", "wangwu", "boy", "1989-2-14 "); studcollect s; S. add (S1); S. add (S2); S. add (S3); Student * PS = S. find ("1002"); If (PS) PS-> display (); Return 0 ;}

The code running example is as follows:

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.