STL

前言

(mathcal{STL})(mathcal{Standard}) (mathcal{Template}) (mathcal{Library}) の简称,中文名标准模板库

在C++标准中,STL被组织为下面的13个头文件:<algorithm><deque><functional><iterator><vector><list><map><memory.h><numeric><queue><set><stack><utility>

stack

头文件:#include<stack>
定义:stack<int>s;
压栈:s.push(x);
弹栈:s.pop();
访问栈顶元素:x=s.top();
访问栈中元素个数:x=s.size();

queue

头文件:#include<queue>
定义:queue<int>q;
入队:q.push(x);
出队:q.pop();
访问队首元素:x=q.front();
访问队尾元素:x=q.back();

map

头文件:#include<map>
定义:map<int,string>m;(前者为下标类型,后者为存储类型)
与数组用法相同,示例:

#include<iostream>
#include<map>
using namespace std;
map<int,char>m;
int main()
{
    a[1]='q';
    a[2]='w';
    a[3]='q';
    for(int i=1;i<=3;++i)
        cout<<a[i];
    return 0;
}

vector

(mathcal{STL}) 中的数组,没有确定容量,支持随机访问。
头文件:#include<vector>
定义:vector<int>v;
插入元素:v.push_back(x);
访问元素:x=v[y];

  • vector下标从(0)开始。
#include <bits/stdc++.h>    // <vector>
using namespace std;
vector<int>v;
int main(void)
{
    v.push_back(1);
    v.push_back(2);
    v.pop_back();
    for(int i=0;i<v.size();i++) cout<<v[i]<<endl;
    return 0;
}

deque

双端队列,支持在两端插入。
头文件:#include<deque>
定义:deque<int>d;
在队首插入元素:d.push_front(x);
在队尾插入元素:d.push_back(x);
获取队列长度:x=d.size();
弹出队首元素:d.pop_front();
弹出队尾元素:d.pop_back();
清除所有元素:d.clear();

#include<deque>
#include<cstdio>
using namespace std;
deque<int>d;
int main()
{
    d.push_back(1);
    d.push_front(2);
    printf("size:%d
",d.size());
    d.push_front(3);
    for(int i=1;i<=2;++i)
        printf("%d
",d.front()),d.pop_front();
    d.clear();
    return 0;
}

优先队列/堆

嗯对,优先队列和堆在(mathcal{STL}) 里是一样的。
头文件:#include<queue>
小根堆/最小优先队列定义:

priority_queue<int, vector<int>, greater<int> > q;

大根堆/最大优先队列定义:

priority_queue< int >p;

插入元素:q.push(x);
弹出最大/小元素:q.pop();
访问最大/小元素:x=q.top();

示例:

#include<vector>
#include<deque>
#include<cstdio>
#include<queue>
using namespace std;
priority_queue<int, vector<int>, greater<int> > q;
int n,x,y,ans;
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
        scanf("%d",&x),q.push(x);
    for(int i=1;i<n;++i)
    {
        x=q.top();
        q.pop();
        y=q.top();
        q.pop();
        q.push(x+y);
        ans+=x+y;
    }
    printf("%d
",ans);
    return 0;
}

The end.

原文地址:https://www.cnblogs.com/CM-0728/p/13403730.html