STL

视频讲解:https://www.bilibili.com/video/BV1qU4y1T7yJ?share_source=copy_web

容器:

顺序式容器:

vector:变长数组,原理倍增,计算机分配空间所消耗的时间只与分配次数有关,与你分配空间大小无关。巅峰内存消耗为3倍。

#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;
struct node{
	int a;
	string s;
};
int main(){
	vector <int> v;//定义 
	
	int x=10;
	v.push_back(x);
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);//插入操作 
	
	vector <node> v1;//定义自定义类型 
	v1.push_back({1,"asd"});
	
	cout<<v.size()<<endl;//vecotr大小
	 
	if(!v.empty()){		//vector是否为空 
		cout<<"true"<<endl;
	}
	
	
	for(int i=0;i<v.size();i++){//遍历1 
		cout<<v[i]<<endl;
	}
	
	for(vector <int>::iterator i=v.begin();i!=v.end();i++){//遍历2 
		cout<<*i<<endl;
	} 
	
	for(auto i:v){ //for range遍历 -std=c++11
		cout<<v[i]<<endl; 	
	}
	
	v.clear();//清空 
	if(v.empty())cout<<"clear"<<endl;
	cout<<v.front()<<' '<<v.back()<<endl;//头和尾
	
	
	return 0;
} 

pair:

#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;

pair <int,char> a;
int main(){
	a={1,'a'};
	cout<<a.first<<endl;
	cout<<a.second;
	//排序会按第一关键字排序,再按第二关键字,字典序 
	
	return 0;
} 

string:

#include<iostream>
#include<cstdlib>
#include<vector>
#include<stdio.h>
#include<string>
using namespace std;

int main(){
	string s="abcdefg";
	string s1="b";
	cout<<s+s1<<endl;//加法操作 
	printf("%s",s.c_str());//c语言输出string 
	cout<<s.substr(1,2); //截取 
	return 0;
} 

queue:

FIFO:先进先出

#include<iostream>
#include<cstdlib>
#include<vector>
#include<stdio.h>
#include<string>
#include<queue> 
using namespace std;

int main(){
	queue <int> q;//定义 
	
	int x=3;
	q.push(1);//插入 
	q.push(2);
	q.push(x);
	
	cout<<q.front()<<endl;//队头
	q.pop();//弹出
	cout<<q.front()<<endl;
	cout<<q.back()<<endl;//队尾 
	cout<<q.size();//大小 
	if(q.empty())cout<<"YES"<<endl;//是否为空 
    //遍历方式:迭代器遍历和vecotr一样
	return 0;
} 

priority_queue:

优先队列,原理是二叉堆,默认是大根堆(理解为排好序的队列,自定义排序规则,插入和弹出都是O(logN)时间复杂度)。

#include<iostream>
#include<cstdlib>
#include<vector>
#include<stdio.h>
#include<string>
#include<queue> 
using namespace std;
struct node{
	int x;
	char c;
	bool operator < (const node &y)const{//重载小于号
		return x>y.x;
	}
};
priority_queue <int> q;//默认大根堆 
priority_queue<int,vector<int>,greater<int> >q1;//从小到大
priority_queue<int,vector<int>,less<int> >q2;//从大到小
priority_queue <node> q3; 
int main(){
	int x=3;
	q.push(2);//插入 
	q.push(1);
	q.push(x);
	q3.push({2,'a'});
	q3.push({1,'x'});
	q3.push({3,'c'});
	while(q.size()){//遍历,大小,队头,弹出 
		cout<<q.top()<<' ';
		q.pop();
	}
	while(q3.size()){//遍历,大小,队头,弹出 
		cout<<q3.top().x<<' ';
		q3.pop();
	}
	return 0;
} 

stack

栈:先进后出

#include<iostream>
#include<cstdlib>
#include<vector>
#include<stdio.h>
#include<string>
#include<queue> 
#include<stack>
using namespace std;
int main(){
	stack <int> s;//定义
	
	s.push(1);//插入 
	s.push(2);
	s.push(3);
	while(s.size()){//大小 
		cout<<s.top();//栈顶 
		s.pop();//弹出 
	} 
	
	 
	return 0;
} 

0 comments

No comments so far...