STL模板总结

STL有时候有些函数总是忘记,故记下来常看看

我的易忘点

  • pair头文件utility

  • 无序map头文件unordered_map

  • 优先队列拼写 priority_queue

priority_queue

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <queue>   // 优先队列 头文件
// 升序队列
priority_queue<int, vector<int>, greater<int> > q;
// 降序队列
priority_queue<int, vector<int>, less<int> > q;

// 优先队列中结构体的排序
//重写仿函数
struct cmp_queue 
{
    bool operator() (PII a, PII b) 
    {
        if(a.first > b.first)
            return true;
        if(a.first < b.first)
            return false;
        if(a.second > b.second) return true;
            return false;
    }
};

priority_queue<PII, vector<PII>,cmp_queue> q;
// 参考文献:https://blog.csdn.net/weixin_36888577/article/details/79937886

pair

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <utility>    // 头文件
#include <iostream>
using namespace std;

int main(){
  pair<int,int> mm;   // 创建pair
  mm.first = 1;       // 给第一个元素赋值
  mm.second = 2;      // 给第二个元素赋值
  cout << mm.first << " " << mm.second << endl;
}

Vector

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <vector>    // 头文件
#include <iostream>
#include <algorithm>
using namespace std;

int main(){
  vector<int> v1;     // 空vector
  vector<int> v2(4);  // 大小为4的空vector
  vector<int> v3{1,2,3};  //  vector内容为{1,2,3}
  v1.push_back(3);    // 添加元素
  v2.size();          // 查看大小
  sort(v3.begin(),v3.end()); // 进行排序
}

Stack

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <stack>    // 头文件
#include <iostream>
using namespace std;

int main(){
  stack<int> s;  // 定义一个空栈
  s.push(1);     // 向栈内添加元素
  s.top();       // 查看栈顶元素
  s.pop();       // 出栈,无返回值
  s.size();      // 查看元素个数
}

map

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <map>           // 树状map,有序,按照第一个键排序
#include <unordered_map> // 哈希map,无序
#include <iostream>
using namespace std;

int main(){
  map<int,int> m1;
  unordered_map<int,int> m2;

  m1[1] = 1;
  m1[5] = 2;
  m1[3] = 3;
  cout << "Map" << endl;
  for(auto x:m1){
    cout << x.first << " " << x.second << endl;
  }

  m2[1] = 1;
  m2[5] = 2;
  m2[3] = 3;
  cout << "unordered_Map" << endl;
  for(auto x:m2){
    cout << x.first << " " << x.second << endl;
  }
}

Set

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <set>            // 有序set
#include <unordered_set>  // 无序set
#include <iostream>
using namespace std;

int main(){
  set<int> s1;
  unordered_set<int> s2;
  s1.insert(1);           // 插入元素
  s2.insert(1);
}
updatedupdated2022-03-112022-03-11