Detailed explanation of C++ vector container

The basic concept of vector container

Function: The function of the vector container is very similar to that of an array, and it can be regarded as an array when used

The difference between vector and ordinary array:
1. The array is static and the length cannot be changed, while the vector can be dynamically expanded to increase the length
2. The data in the array is usually stored on the stack, while the data in the vector is stored on the heap

Dynamic expansion: (this concept is very important)
dynamic expansion is not to continue the new space after the original space, but to find a larger memory space than the original, copy the original data to the new space, and release the original space

Note: header files must be included before using vector#include<vector>

insert image description here

1. The constructor of vector

Function prototype:
1. vector<T> v ;//Use template class, default constructor
2. vector(v.begin(),v.end());//Copy the elements in [v.begin(), v.end()) range to itself
3. vextor(n,elem);//Copy n elems to itself
4. vector(const vector &v) ;//copy constructor

In order to facilitate the test, we first define a printout function, which is realized by an iterator. This function will be used frequently below, and the iterator can be understood as a pointer

void printVector(vector<int>& v)
{
    
    	//利用迭代器打印 v
	for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
	{
    
    
		cout << *it << " ";
	}
	cout << endl;
}

Test Case:

void text01()
{
    
    
	vector<int> v1;                       //调用1
	for (int i = 0; i < 5; ++i)
	{
    
    
		v1.push_back(i);//向v1末尾添加数据
	}
	vector<int> v2(v1.begin(), v1.end());//调用2
	vector<int> v3(5, 5);                //调用3
	vector<int> v4(v3);                  //调用4
	cout << "打印v2: ";
	printVector(v2);
	cout << "打印v3: ";
	printVector(v3);
	cout << "打印v4: ";
	printVector(v4);
}

Test Results:
insert image description here

2. Vector assignment operation

Function prototype:
1. vector& operator=(const vector &v);//Overload assignment operator
2. assign(v.begin(),v.end());//Assign the elements in [v.begin(), v.end()) range to itself
3. assign(n,elem);//Assign n elems to itself

Test Case:

void text02()
{
    
    
	vector<int> v1,v2;
	for (int i = 0; i < 5; ++i)
	{
    
    
		v1.push_back(i);
	}
	v2 = v1;                        //调用1,赋值运算符重载
	vector<int> v3,v4;
	v3.assign(v1.begin(), v1.end());//调用2,区间赋值
	v4.assign(5, 9);                //调用3
	cout << "打印v2: ";
	printVector(v2);
	cout << "打印v3: ";
	printVector(v3);
	cout << "打印v4: ";
	printVector(v4);
}

Test Results:
insert image description here

3. The capacity and size of vector

Function prototype:
1. empty();//Judge whether the container is empty, return 1 if it is empty, otherwise return 0
2. capacity();//Return the capacity of the container
3. size();//Return the size of the container, that is, the number of elements in the container
4. resize(int num);//Reset The length of the specified container is num. If the container becomes longer, the new position will be filled with the default value of 0. If the container becomes shorter, the elements at the end that exceed the length of the container will be deleted. 5. //Re-specify the length of the container as num, if the
container resize(int num,int elem);becomes If it is long, fill the new position with elem. If the container becomes shorter, the elements at the end that exceed the length of the container will be deleted.
resize feature: long assignment, short truncation

Test Case:

void text03()
{
    
    
	vector<int> v1;
	if (v1.empty())//调用1,如果容器为空,则给其赋值
	{
    
    
		for (int i = 0; i < 5; ++i)
		{
    
    
			v1.push_back(i);
		}
	}
	cout << "打印v1: ";
	printVector(v1);
	cout << "v1的容量为:" << v1.capacity() << endl;//调用2
	cout << "v1的大小为:" << v1.size() << endl;//调用3

	//重新指定容器大小使其变长
	v1.resize(10);       //调用4,增加的长度默认值为0
	cout << "调用4,增加长度后,打印v1: ";
	printVector(v1);
	v1.resize(15, 9);    //调用5,增加的长度赋值为9
	cout << "调用5,增加长度后,打印v1: ";
	printVector(v1);
	//重新指定容器大小使其变短
	v1.resize(10);       //调用4,删除了上一步中最后赋值为9的5个长度
	cout << "调用4,减小长度后,打印v1: ";
	printVector(v1);
	v1.resize(5, 9);     //调用5,删除了上一步中默认值为0的5个长度
	cout << "调用5,减小长度后,打印v1: ";
	printVector(v1);
}

Test Results:
insert image description here

4. Vector insertion and deletion

Function prototype:
1. push_back(ele);//Insert element ele at the end
2. pop_back();//Delete the last element
3. insert(const_iterator pos,ele);//Insert an element ele at the position pos pointed to by the iterator
4. insert(const_iterator pos,int count,ele);//Insert count elements at the position pos pointed to by the iterator Element ele
5. erase(const_iterator pos);//Delete the element pointed to by the iterator
6. erase(const_iterator begin,const_iterator end);//Delete the element between the iterator from begin to end
7. clear();//Delete all elements in the container

Test Case:

void text04()
{
    
    
	vector<int> v1;
	for (int i = 0; i < 5; ++i)
	{
    
    
		v1.push_back(6);//调用1,尾部插入元素6
	}
	cout << "打印v1: ";
	printVector(v1);
	v1.pop_back();//调用2,删除最后一个元素
	cout << "调用2,删除最后一个元素后,打印v1: ";
	printVector(v1);
	v1.insert(v1.begin(),20);//调用3,在首位插入20
	cout << "调用3,在首位插入20,打印v1: ";
	printVector(v1);
	v1.insert(v1.end(), 3, 20);//调用4,在尾部插入3个20
	cout << "调用4,在尾部插入3个20,打印v1: ";
	printVector(v1);
	v1.erase(v1.begin()); //调用5,在首位删除一个元素
	cout << "调用5,在首位删除一个元素,打印v1: ";
	printVector(v1);
	v1.erase(v1.begin(),v1.end()); //调用6,删除首位到末尾所有元素,也就是删除全部元素
	cout << "调用6,删除首位到末尾所有元素,打印v1: ";
	printVector(v1);
	v1.clear();//调用7,清空所有元素
}

Test Results:
insert image description here

5.vector data access

Function prototype:
1. at(int idx);//Return the data pointed by the index idx
2. operator[];//Return the data pointed by the index in []
3. front();//Return the first element in the container
4. back();//Return the last element in the container

Test Case:

void text05()
{
    
    
	vector<int> v;
	for (int i = 0; i < 5; ++i)
	{
    
    
		v.push_back(i);
	}
	//利用at访问v
	cout << "调用1,打印v: ";
	for (int i = 0; i < v.size(); ++i)
	{
    
    
		cout << v.at(i) << " ";//调用1
	}
	cout << endl;
	//利用[]访问v
	cout << "调用2,打印v: ";
	for (int i = 0; i < v.size(); ++i)
	{
    
    
		cout << v[i] << " ";//调用2
	}
	cout << endl;
	cout << "容器中第一个元素是:" << v.front() << endl;//调用3
	cout << "容器中最后一个元素是:" << v.back() << endl;//调用4
}

Test Results:
insert image description here

6.vector interchange container

Function prototype:
swap(v);//Container v and the current container are interchanged

Test Case 1: Basic Usage

void text06_1()
{
    
    
	vector<int> v1,v2;
	for (int i = 0; i < 10; ++i)
	{
    
    
		v1.push_back(i);
		v2.push_back(9 - i);
	}
	cout << "交换前:" << endl;
	printVector(v1);
	printVector(v2);
	cout << "交换后:" << endl;
	v1.swap(v2);   //调用互换函数
	printVector(v1);
	printVector(v2);
}

Test Results:
insert image description here

Test Case 2: Practical Use

void text06_2()
{
    
    
	vector<int> v;
	for (int i = 0; i < 1000; ++i)
	{
    
    
		v.push_back(i);
	}
	cout << "初始时:" << endl;
	cout << "v的容量:" << v.capacity() << endl;
	cout << "v的大小:" << v.size() << endl;
	
	cout << "重新指定空间后:" << endl;
	v.resize(10);
	cout << "v的容量:" << v.capacity() << endl;
	cout << "v的大小:" << v.size() << endl;

	//巧用swap收缩内存
	cout << "swap收缩内存后:" << endl;
	vector<int>(v).swap(v);   //vector<int>(v) 是创建一个匿名对象,并拷贝v的数据
	                          //以此匿名对象与v交换,交换完后系统自动删除匿名对象
	cout << "v的容量:" << v.capacity() << endl;
	cout << "v的大小:" << v.size() << endl;
}

Test Results:
insert image description here

7. Vector reserved space

Function: reduce the number of expansions of vector during dynamic expansion
. Every time push_back(v) is used, if the size of container v exceeds the capacity of v, the system will perform a dynamic expansion of v. As for how much space to expand, it is determined by the system

Function prototype:
reserve(int len);//The container reserves the length of len elements, that is, the capacity is expanded to len, the
reserved position is not initialized, and it is also inaccessible

Test Case:

void text07()
{
    
    
	vector<int> v1,v2;
	v2.reserve(10000);//给v2设置预留空间,v1不设置

	//对比v1,v2,系统需要动态扩容多少次
	int num1 = 0;       //扩容次数
	int num2 = 0;       
	int capacity1 = 0;  //容量大小
	int capacity2 = 0;
	for (int i = 0; i < 10000; ++i)
	{
    
    
		v1.push_back(i);
		if (capacity1 != v1.capacity())//计算扩容次数,当容量不相等时,证明系统扩容了
		{
    
    
			capacity1 = v1.capacity();
			++num1;
		}

		v2.push_back(i);
		if (capacity2 != v2.capacity())
		{
    
    
			capacity2 = v2.capacity();
			++num2;
		}
	}
	cout << "系统对v1扩容" << num1 << "次" << endl;
	cout << "系统对v2扩容" << num2 << "次" << endl;
}

Test Results:
insert image description here

write at the end

The vector container is one of the most commonly used containers in C++. I used it often before I really learned it. After seeing how others use it, I probably know it a little bit, but I didn’t know its specific principles at that time. Now After the study, I have summarized the specific usage of vector in detail for everyone to learn together. If you like it, please like, collect and pay attention!

おすすめ

転載: blog.csdn.net/qq_52324409/article/details/121000029