The usage of vector in C++ STL

Construct a dynamic array using vector

vector<T> vec. This defines a dynamic array vecof storage type data called . TWhere Tis the data type to be stored in our array, which can be int, float,double

 

vectorSummary of C++  methods:

method Function
push_back add an element at the end
pop_back Pop an element at the end
size get length
clear empty

 


Advanced usage of vector

 

Dynamic arrays can store not only basic data types, but also custom data types, such as structures.


struct Student {
string name; // 名字
int age; // 年龄
};

int main() {
	vector<Student> class1; // 班级
 	Student stu1, stu2;// 学生1,学生2
 	stu1.name = "xiaoli";
 	stu1.age = 12;
	stu2.name = "jinxin";
	stu2.age = 25;
	class1.push_back(stu1);
	class1.push_back(stu2);
	return 0;
}

 


Using the vector's constructor

We know that we can push_back()add an element to a dynamic array by . Suppose we need a dynamic array of length n, all ones. We can write like below.

 

int n = 10;
vector<int> vec;
for (int i = 0; i < n; i++) {
    vec.push_back(1);
}

In fact, we can quickly build such a dynamic array through a constructor

 

int n = 10;
vector<int> vec(n, 1);

 

In the above code, when we define one vector, we call the constructor. The first parameter represents the length of the initial dynamic array, and the second parameter represents the value of each element in the initial array. If the second parameter is not passed, the initial value is 0.

The above way of writing the constructor is equivalent to using the loop. By using the constructor reasonably, the amount of code can be reduced.

 


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326389260&siteId=291194637