Details of using C++ vector

Vector is part of the C + + standard template library, which is occasionally translated as "container" in Chinese. It is a multi-functional template class and function library that can operate a variety of data structures and algorithms. Vector is a dynamic array that can store any type of data, and can increase and compress data. The header file "include < vector > needs to be included when using.

1.vector initialization

1.1 there are three main methods for vector initialization.

(1)vector <type> a;//Do not initialize container(There is no difference between container and array in this paper)Size, that is, to create an empty container, which can be push_back Put the element behind the container.

(2)vector <type> a(10);//The initialization container size is 10. If it is int, float and other types, the default initialization value is 0. The default initialization value of char type is a space. The string type has no initialization value (even if it is an empty container size, it is still 10).

vector<int> a(10,1);//The initialization container size is 10 and the values are all 1.

(3)vector<int> a={3,4,5,6};//Initialize the container to {3,4,5,6}.

Be careful:

(1) Only the initialized space can be assigned, such as

vector <int> a;
a[1]=1;

This is not right, and it is also the most easy mistake for beginners. At this time, a does not initialize any space. The size and capacity of a are all 0, and a[1] does not exist. Naturally, a[1] cannot be assigned. However, you can push back to insert elements, and the corresponding container size will be automatically increased by 1.

(2) After using vector < int > A (10) initialization, the first 10 elements will have a default initial value of 0. At this time, the element inserted through push back will be at a[10] position (the 11th).

1.2 creation of multidimensional array

As mentioned earlier, vector is a dynamic array that can store any type. Since it is any type, it naturally includes vector itself.

(1) Initialize space for all dimensions

vector<vector<int>>v(5, vector<int>(6));//Initialize a two-dimensional array with 5 rows and 6 columns, and the values are all 0

It can also be seen that there are 5 vector containers in the v container, each of which contains 6 int data, and the initialization value is all 0.

cout << v.size() << endl;//Output is 5.
cout << v[0].size() << endl;//Output is 6.
cout << v[0][0] << endl;//Output is 0.

(2) only one dimension initialization space

vector<vector<int>>v(5);//Initialize a two-dimensional array with 5 rows, and the number of rows and columns is uncertain

Since the number of columns is the initialization space, which is equivalent to that there are 5 vectors in the container of v. the elements in each vector are uncertain. Therefore, v[0][0]=1 cannot be used for assignment. You can use v[i].push_back() to put data into the ith container (I start from 0) (i.e. put data into the ith row).

Since the number of array rows has been initialized, v[i] can be assigned directly, that is, the i-th element of V (in this case, the element is vector < int > type) can be assigned through v[i]=v2(v2 is another vector < int > type container).

(3) All dimensions are uninitialized

vector<vector<int>>v;//Initializes a two-dimensional array with uncertain rows and columns

You can also look at a container V, in which vector < int > type elements are stored. The number of storage elements is unknown. The number of int data contained in vector < int > type elements is also unknown. Therefore, neither v[0][0]=1 nor v[i]=v2(v2 is another vector < int > type container) can be used to assign a value to the ith element of V (in this case, the element is vector < int > type).

Only v.push back (vi), vi is a container of type vector < int >.

1.3 access to vector element

(1) Access via iterator

for (vector<int>::iterator it = a.begin();it != a.end(); ++it) 
{
    cout << *it << ' ';
}

(2) access through subscript

for(int i=0;i<a.size();++i)
{
    cout<<a[i]<<" ";
}

(3) use iterator as pointer

for (int i = 0; i < v2.size(); i++)
{
	cout << *(v2.begin() + 1) << " ";
}

2. Some important operations of vector object

(1)a.assign(2,3);//Assign 2 elements to a with a value of 3, relative to reinitialization. However, if the original a.capacity() is greater than 2, the capacity will not decrease after reallocation.
(2)a.assign(b.begin(),b.begin()+2);//Assign the first two values of B to a, excluding b.begin()+2. Where b.begin() can be a pointer to an array of other types
(3)a.back();//Returns the last element of a. if it does not exist, an error will be reported
(4)a.front();//Returns the first element of a. if it does not exist, an error will be reported
(5)a[i]; //Returns the ith element of a if and only if a[i] exists
(6)a.clear();//Empty the element in a, the size becomes 0, and the capacity does not decrease
(7)a.empty();//Judge whether a is empty, return true if it is empty, return false if it is not empty
(8)a.pop_back();//Delete the last element of a vector
(9)a.erase(a.begin()+1,a.begin()+3);//Delete the first (from 0) to the second element in a, that is, the deleted element starts from a.begin()+1 (including it) to a.begin()+3 (excluding it)
(10)a.push_back(5);//Insert an element after the last vector of a with a value of 5
(11)a.insert(a.begin()+1,5);//Insert the value 5 in the position of the first element of a (from the 0 th), for example, a is 1,2,3,4, and after inserting the element, it is 1,5,2,3,4
(12)a.insert(a.begin()+1,3,5);//Insert 3 numbers in the position of the first element of a (counting from the 0) with values of 5

(13)a.insert(a.begin()+1,b+3,b+6);//b is an array. Insert the third element of b to the fifth element (excluding b+6) at the first element of a (counting from the 0th). For example, b is 1,2,3,4,5,9,8, and then 1,4,5,9,9,2,3,4,5,9,8
(14)a.size();//Returns the number of elements in a;
(15)a.capacity();//Returns the total number of elements a can hold in memory

(16)a.rezize(10);//Adjust the number of existing elements of a to 10, more elements will be deleted, less elements will be supplemented, and its value will be random, which will not reduce the a.capacity()
(17)a.rezize(10,2);//Adjust the number of existing elements of a to 10, delete more elements, and supplement less elements, with a value of 2
(18)a.reserve(100);//Expanding a's capacity to 100 can avoid multiple memory capacity expansion operations (when a's capacity is insufficient, the computer will automatically expand, which will certainly reduce performance)
(19)a.swap(b);//b is the vector, exchanging the elements in a and b as a whole (including capacity)
(20)a==b; //b is the vector, and the comparison operation of vector also includes! =, > =, < =, >, ({2,3,0} > {2,3})

3. Common algorithms

STL is mainly divided into three parts: container, iterator and algorithm. Iterator is the bridge between container and algorithm. Iterators are very similar to pointers. a.begin() points to the first element in a, and a.end() points to the position after the last element in a.

The header file should be included when using

(1) sort(a.begin(),a.end()); / / arrange the elements in a from a.begin() (including it) to a.end() (excluding it) from small to large

If you want to sort from large to small, you can define a comparison function:

bool flag(const int &a, const int &b)
{
	return a > b;
}

Call sort(a.begin(),a.end(),flag) when sorting.

Of course, you can sort from small to large, and then reverse the container.

(2) reverse(a.begin(),a.end()); / / invert the elements in a from a.begin() (including it) to a.end() (excluding it), but do not arrange them. For example, the elements in a are 1, 3, 2, 4, 4, 2, 3, 1 after inversion

(3) find(a.begin(),a.end(),10); / / find 10 in the elements from a.begin() (including it) to a.end() (excluding it) in a, and return its position in the vector if any

4. Precautions

4.1.4.capacity

a.size() will become the copied container size after re assignment by a.assign; a=b; a={1,2,3} and a.capacity() will not decrease.

For example:

vector<int> a(10);
a={1,2,3};//At this time, a.size() becomes 3, and a.capacity() is still 10

For example, you first allocate 10000 bytes, and then erase the last 9999, leaving a valid element, but the memory occupied

Use is still 10000. All memory space can only be reclaimed by the system when the vector is deconstructed.

Destructor ~ vector()

Destroy container objects and reclaim all allocated memory

4.2.a.size() return value is unsigned integer

vector<int>num = {};
int i = num.size() - 1;

cout << i << endl;//Convert it to int data output
cout << num.size() - 1 << endl;//Do not convert it to int data output

The output is:

When a.size() is 0, a.size()-1 will become a large number. If you run the following code:

for(int i=0;i<vector.size()-1;i++)

It will become a dead cycle. To solve it, just cast its type.

4.3 iterators and pointers

Iterators are very similar to pointers, and they are the exclusive pointers of STL containers.

For example, you can output the value of a[0] through * a.begin(), but a.begin() is not the address of a[0], and a.begin() cannot output. If you want to output a[0] address, you need cout < & a[0].

Most of the algorithms used by vector can also be used for ordinary arrays (overloaded). For example, sort can also be used for ordinary array sorting. At this time, the input becomes a pointer:

int a[5] = { 2,4,1,4,6 };
sort(a, a + 5);
for (int i = 0; i < 5; i++)
{
	cout << a[i] << " ";
}

 

Reference: https://blog.csdn.net/msdnwolaile/article/details/52708144

            https://blog.csdn.net/fanyun_01/article/details/56842637

            https://baike.baidu.com/item/vector/3330482?fr=aladdin

Published 31 original articles, praised 142, visited 10000+
Private letter follow

Tags: less

Posted on Fri, 07 Feb 2020 06:17:40 -0500 by h.a.visser