STL (2) container (under Vector)

vector constructor

Vector construction diagram:
insert image description here
Constructor:
insert image description here

vector<int>v1;//第一种
vector<int>v2(v1.begin(),v1.end());//第二种
vector<int>v3(10,100);//构造v3是10个100
vector<int>v4(v3);//拷贝构造

Vector assignment operation

insert image description here

vector<int>v2;
v2=v1;//v1是有值的vector

Vector capacity and size

insert image description here

insert and delete

insert image description here

Vector data access

insert image description here

for(i=0;i<v1.size();i++)//方法一
{
    
    
	cout<<v1[i];
}
for(i=0;i<v1.size();i++)//方法二
{
    
    
	cout<<v1.at(i);
}

Vector container calls

Function function:
realize the exchange of elements in two containers.
insert image description here

v1.swap(v2);//实现v1和v2元素互换。

Practical use:
clever use of swap can shrink the memory space;
if the capacity of v is 10000, but the actual element size is only 3;
first set the anonymous object x, the size of the anonymous object is the size of the actual element of v, after v and x are exchanged, the anonymous object will be The size is 10000, the actual size is 3, and the size and element of v are both 3. The anonymous object system will automatically recycle it for us, so there is no need to worry about wasting space.
insert image description here
insert image description here

Vector reserved space

Function: reduce the number of dynamic expansion.
insert image description here

v1.reserve(100);

Guess you like

Origin blog.csdn.net/weixin_45866980/article/details/126383680