本文总结一些C++中STL常用的应用。以下的部分内容针对程序设计比赛,建议与代码相伴一起服用!
关于STL的概念,在这里不做赘述,事不宜迟,来啦。
- 数据结构部分
1.栈(Stack)
栈作为基本数据结构,具有后进先出的特点。
使用方法:
引入头文件:include<stack>
定义一个站栈:stack <类型> 栈名;如: stack <int> s;
判断栈是否为空:s.empty();
入栈:s.push(element);
出栈:s.pop(element); 值得注意:出栈操作并没有任何返回值。
取栈顶:s.top();取栈顶即返回栈顶元素。
返回栈中拥有的元素个数:s.size();
简单看看各操作:
stack <int> s;
while(!s.empty()){
s.pop();
}
for(int i = 0;i<10;i++){
s.push(i);
}
while(!s.empty()){
cout<<s.top()<<endl;
s.pop();
}
2.队列(Queue)
关于普通的队列,应用场景并不多(鄙人之见)。所以在这里介绍到的是优先队列。优先队列,即该队列可以按照你的需要对队列元素进行排序。
使用方法:
定义一个优先队列:priority_queue <int> pq; 与栈类似
判断一个队列是否为空: empty();
队头元素出队: pop();
插入一个元素:push();
返回队列中拥有的元素个数:size();
返回优先队列的队顶元素:top();
优先队列可自定义优先级:
优先队列的完整参数其实如下:
priority_queue<Type, Container, Functional>其容器默认为vector,优先级默认是降序,自定义升序可以如下:
普通的自定义方法
struct cmp1{
bool operator()(int x,int y){
return x>y;
}
};
很多情况下我们需要自定义结构体,对结构体内元素进行排序。这时需要重写运算符“<”。
struct node{
int x,y;
friend bool operator < (node a,node b){
return a.x>b.x;
}
};
附上一个小小的例子:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct cmp1{
bool operator()(int x,int y){
return x>y;
}
};
struct node{
int x,y;
friend bool operator < (node a,node b){
return a.x>b.x;
}
};
int main()
{
priority_queue <int> pq;
priority_queue <node> dpq;
priority_queue <int,vector<int>,cmp1>dpq1;
int e;
int i=0;
while(i<5){
cin>>e;
pq.push(e);
node n;
n.x = e;
dpq.push(n);
//dpq1.push(e);
i++;
}
cout<<"默认降序:";
while(!pq.empty()){
cout << pq.top()<<" ";
//cout << dpq1.top() << endl;
pq.pop();
//dpq1.pop();
}
cout<<endl;
cout<<"自定义升序:";
while(!dpq.empty()){
cout<<dpq.top().x<<" ";
dpq.pop();
}
cout<<endl;
return 0;
}
- 算法部分
- 排序函数(sort)
C/C++均内置排序函数,使用算法为快速排序。快速排序适合用于处理乱序的数据,其时间复杂度为O(nlogn)。唯一的问题在于快速排序算法是非稳定排序。
需要引入的头文件:#include <algorithm>
该方法的完整参数:sort(start,end,排序方法)其中排序方法默认为升序。
普通的自定义方式:(方法的类型最好与需要排序元素的类型一致)
int cmp1(int x, int y){
return x>y;
}
当然可以使用更为灵活的结构体排序:
如下为先对结构体的x进行排序,当x相同时对y进行排序。
struct node{
int x,y;
};
int cmp2(node n1, node n2){
if(n1.x==n2.x){
return n1.y>n2.y;
}
return n1.x>n2.x;
}
附上一个小例子:
#include <iostream>
#include <algorithm>
using namespace std;
int cmp1(int x, int y){
return x>y;
}
struct node{
int x,y;
};
int cmp2(node n1, node n2){
if(n1.x==n2.x){
return n1.y>n2.y;
}
return n1.x>n2.x;
}
int main()
{
int a[20];
int b[20];
int e;
int i = 0,j = 0;
node nx[20];
while(i<10){
cin>>e;
a[i]=e;
b[i]=e;
nx[i].x = i;
nx[i].y = e;
i++;
}
sort(a,a+10);
sort(b,b+10,cmp1);
sort(nx,nx+10,cmp2);
cout<<"默认升序:";
while(j<10){
cout <<a[j]<<" ";
j++;
}
cout<<endl;
cout<<"自定义降序:";
j = 0;
while(j<10){
cout<<b[j]<<" ";
j++;
}
cout<<endl;
cout<<"结构体排序:"<<endl;
j = 0;
while(j<10){
cout<<nx[j].x<<" "<<nx[j].y<<endl;
j++;
}
cout<<endl;
return 0;
}
写的比较少,持续更新。