Technology Sharing

【Fall in love with C】Detailed explanation of vector usage

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina


Hello~ Students, this article will explore the vector container in C. As one of the most commonly used dynamic arrays in the Standard Template Library (STL), vector provides flexible element storage and efficient access methods. We will start with the basics and gradually learn its creation, initialization, traversal, space management, and addition, deletion, query and modification operations. Through detailed examples and analysis, I hope to help readers fully understand and master the use skills and precautions of vector.

1: Vector Introduction

vectordocument

  1. A vector is a sequence container that represents an array of variable size.
  2. Just like an array, a vector also uses contiguous storage space to store elements. This means that you can use subscripts to access the elements of a vector, just as efficiently as an array. However, unlike an array, its size can be changed dynamically, and its size will be automatically handled by the container.
  3. Essentially, vector uses a dynamically allocated array to store its elements. When new elements are inserted, this array needs to be resized to increase the storage space. This is done by allocating a new array and then moving all the elements to this array. This is a relatively expensive task in terms of time, because the vector does not resize every time a new element is added to the container.
  4. Vector allocation strategy: vector allocates some extra space to accommodate possible growth, because the storage space is larger than the actual storage space required. Different libraries use different strategies to balance the use of space and reallocation. But in any case, the reallocation should be in logarithmic growth intervals, so that inserting an element at the end is done in constant time complexity.
  5. Therefore, vectors take up more storage space in order to gain the ability to manage storage space and grow dynamically in an efficient manner.
  6. Compared with other dynamic sequence containers (deque, list and forward_list), vector is more efficient when accessing elements, and it is relatively efficient to add and delete elements at the end. For other deletion and insertion operations that are not at the end, the efficiency is lower. It is better than the unified iterator and reference of list and forward_list.


The three realms of using STL: being able to use, understanding, and being able to expand. So when we learn vector below, we will also learn it in this way.

2: Creation and initialization of vector

To package header file#include