[C++ Elementary]: Basic introduction to vector

1. Vector (vector) introduction

insert image description here

Two.vector prototype

insert image description here
insert image description here

Vector is mainly divided into two template parameters, one is T, and T is to instantiate the data type (essentially an array). The second parameter is Alloc. Alloc is a space configurator, that is, a memory pool and it has a default parameter allocator. If someone thinks this memory pool is not suitable, it can be modified through it (generally, it is not necessary to manage) .

3. Structure

insert image description here

insert image description here

4. The difference between reserve and resize

insert image description here

insert image description here

These two interfaces re-adjust the capacity. If n is less than the current capacity, the capacity will remain unchanged, otherwise, the capacity will be expanded to n. Note that this expansion is performed directly according to the type, not the number of bytes expanded.

difference between the two

insert image description here

insert image description here

insert image description here

insert image description here

We can see that when using reserve to open space and then using [] to access, an assertion error will occur. This is because size is generally used as valid data in STL, and the first piece of code when [] is overloaded is assert(i<size). Reserve is just a simple open space, and does not change the size of the size, so an assertion error naturally occurs during access. And resize not only opens up space but also changes the size, so it can be accessed normally. For reserve we should use insert to insert one by one.

insert image description here

insert image description here

Five. Two-dimensional array

insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/m0_73790767/article/details/131628243