C++ dynamic array Vector1

Introduction

Vector is a dynamic array in an object-oriented way.
Using the simplest array, dynamic expansion of inserting elements cannot be achieved because of limited capacity.
Insert picture description here

Add tail operation

Use vector containers to easily realize dynamic expansion of inserting elements. Traditional C arrays have limited capacity, and vectors can dynamically manage expansion;

#include <vector>
#include <iostream>
using namespace std;
int main(){
    
    
	vector<int> vec={
    
    1,2,3,4};
	//在尾部进行元素插入操作。
	vec.push_back(5);
}

Traverse operation

You can use the capacity and size methods of vec to view the current capacity of the vector and the number of non-stop elements.

#include <vector>
#include <iostream>
using namespace std;
int main(){
    
    
	vector<int> vec={
    
    1,2,3,4};
	cout<<"size is"<<vec.size()<<endl;
	cout<<"capacity is"<<vec.capacity()<<endl;
	//在尾部进行元素插入操作。
	vec.push_back(5);
	for(int index=0;index<vec.size();++index){
    
    
		cout<<vec[index]<<endl;
	}
	cout<<"size is"<<vec.size()<<endl;
	cout<<"capacity is"<<vec.capacity()<<endl;
	return 0;
}

Insert operation

Insert picture description here

vec.insert(--vec.end(),4);

Delete operation

Insert picture description here

vec.pop_back();//从尾部插入。
vec.erase(vec.end()-1);//从中间移除

Guess you like

Origin blog.csdn.net/yasuofenglei/article/details/108484272