Several ways to initialize vector in c++

In C++, vector is a dynamic array that can freely add and delete elements at runtime. Initializing a vector is the process of creating a vector object and allocating memory space for it. Here are several ways to initialize vector in C++:

  • default constructor

Create an empty vector using the default constructor like this:

std::vector<int> vec; // 创建空vector

This approach can be used to create a vector that needs to be filled later.

  • Constructor with initial element count and value

Create a vector using a constructor with an initial number of elements and values, like so:

std::vector<int> vec(5, 0); // 创建一个包含5个int元素,每个元素都是0的vector

This method will create a vector containing 5 elements of type int with a value of 0.

  • constructor with initial number of elements

The vector is created using a constructor with an initial number of elements, like this:

std::vector<int> vec(8); // 创建一个包含8个未初始化int元素的vector

This method will create a vector containing 8 elements of uninitialized int type.

  • Constructor with an initial list of elements

Create a vector using a constructor with a list of initial elements (In C++, {}initializing a vector with is a convenience method, also known as list initialization.), as follows:

std::vector<int> vec = {1, 2, 3}; // 创建一个包含3个int元素,值分别为1、2、3的vector

This method will create a vector containing 3 int type elements with values ​​1, 2, and 3 respectively.

  • copy or move constructor

A new vector can be created from an existing vector using the copy or move constructor. As follows:

std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2(vec1); // 创建一个与vec1的内容相同的vector
std::vector<int> vec3(std::move(vec2)); // 使用移动构造函数将vec2的所有资源转移给vec3

This is used less often, but in some cases they can be used to optimize code performance.

It should be noted that the initial value provided when initializing the vector needs to match the vector template parameter type or be able to be implicitly converted to the vector template parameter type. If the number of initial values ​​provided exceeds the storage space reserved by vector, then vector will automatically allocate larger storage space to accommodate all elements.

Guess you like

Origin blog.csdn.net/qq_26093511/article/details/131232130