C++ container vector class related operations

C++ container vector related operations

1. Capacity The capacity of a
vector is always greater than or equal to its size. Once the capacity is equal to the size, it is full. Next time there are new elements, the entire vector container will have to find another place to live.
1. c.capacity(); ...how many elements can be saved by c without reallocating memory space
2. c.reserve(); ...allocate memory space that can hold at least n elements

    vector<int> v;
	for (int i = 0; i < 10; i++)
	{
    
    
		v.push_back(i);
		cout << v.capacity() << endl;
	}

Output:

1
2
3
4
6
6
9
9
9
13
请按任意键继续. . .

Two, vector construction and assignment

//赋值
	vector<int> v1;
	vector<int> v2(10, 100);
	printVector(v2);
	
	vector<int> v3(v2.begin(), v2.end());
	printVector(v3);

	//赋值
	vector<int> v4;
	v4.assign(v3.begin(), v3.end());//等价于v4=v3
	printVector(v4);

	int arr[] = {
    
     2,3,4,1,9 };
	vector<int> v5(arr, arr + sizeof(arr) / sizeof(int));

	//swap交换
	v4.swap(v5);
	printVector(v4);

Output:

100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100
2 3 4 1 9
请按任意键继续. . .

Three, vector size operation

vector<int> v1 = {
    
     1,2,5,6,9,56,4,5,11,6 };
	cout << "v1中元素的个数为:" << v1.size() << endl;//size返回容器中元素的个数
	
	if (v1.empty())//判定容器是否为空
	{
    
    
		cout << "v1为空" << endl;
	}
	else
	{
    
    
		cout << "v1不为空" << endl;
	}

	//重新指定容器长度 resize
	v1.resize(11);//重新指定容器的长度,若容器长了,则用默认值填充容器的长度
	printVector(v1);
	v1.resize(3);//如果容器短了,则末尾超出容器长度的元素被删除
	printVector(v1);
	v1.resize(15, 100);//第二个参数是默认填充的值
	printVector(v1);

Output:

v1中元素的个数为:10
v1不为空
1 2 5 6 9 56 4 5 11 6 0
1 2 5
1 2 5 100 100 100 100 100 100 100 100 100 100 100 100
请按任意键继续. . .

Four, vector data access operations

    vector<int> v1 = {
    
     1,2,3,4,5 };
	cout << "v1的第一个元素:" << v1.front() << endl;
	cout << "v1的最后一个元素:" << v1.back() << endl;

Output:

v1的第一个元素:1
v1的最后一个元素:5
请按任意键继续. . .

Five, vector insertion and deletion operations

vector<int> v1 = {
    
     1,2,3,4,5 };
	v1.insert(v1.begin()+1,2, 1000);//第一个参数是迭代器,第二个是个数,第三个是插入元素
	printVector(v1);

	v1.pop_back();//尾部删除
	printVector(v1);

	v1.erase(v1.begin());//删除
	printVector(v1);

	v1.clear();//清空
	printVector(v1);

Output:

1 1000 1000 2 3 4 5
1 1000 1000 2 3 4
1000 1000 2 3 4

请按任意键继续. . .

Six, positive order traversal and reverse order traversal

vector<int> v1 = {
    
     1,2,3,4,5 };
	cout << "正序遍历结果:" << endl;
	printVector(v1);

	cout << "逆序遍历结果:" << endl;
	for (vector<int>::reverse_iterator it = v1.rbegin(); it != v1.rend(); it++)//如果使用逆序遍历的话,需要使用reverse_iterator
	{
    
    
		cout << *it << " ";
	}

Output:

正序遍历结果:
1 2 3 4 5
逆序遍历结果:
5 4 3 2 1 请按任意键继续. . .

Guess you like

Origin blog.csdn.net/Little_XWB/article/details/108023942