汇总了c++ STL 库中常用的API用法
常用API
vector
1 2 3 4 5 6 vector<int > a; a.resize (N); reverse (a.begin (), a.end ()); swap (a[0 ], a[1 ]); a.assign (b.begin (), b.end ()); a.erase (a.begin ()+1 );
sort
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 struct Node { Node (int idx_, int w_, int p1_, int p2_){ idx = idx_; w = w_; p1 = p1_; p2 = p2_; } static bool cmp () { } bool operator <(const Node& data){ return w < data.w; } int idx; int w; int p1; int p2; }; vector<Node> test; sort (test.begin (), test.end ());
string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 string a = "123" ; string b = a.substr (0 ,1 ); string a = string (5 ,'0' ); a.at (0 ); a.resize (N); a.erase (10 , 4 ) a.insert (14 ,6 ,'*' ) a.find ("b" ,5 ) a.erase (0 ,a.find_first_not_of (" " )); a.erase (a.find_last_not_of (" " ) + 1 ); stringstream ss (a) ;string item; while (ss >> item) cout << item << endl; while (std::getline (ss, item, '_' )){ cout << item << endl; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 vector<int > split_string (string& s) { vector<int > re; int p1 = 0 , p2 = 0 ; for (; p2 < s.size (); p2++){ if (s[p2] == '+' || s[p2] == '-' || s[p2] == '*' ){ re.push_back (stoi (s.substr (p1, p2-p1))); re.push_back (s[p2]); p1 = p2+1 ; } } re.push_back (stoi (s.substr (p1, p2-p1))); return re; }
stringstream用法
头文件 include<sstream>
字符串分割函数
1 2 3 4 5 6 7 8 void split (const string s, vector<string>& vs, const char delim= ' ' ) { istringstream iss (s) ; string temp; while (getline (iss,temp,delim)){ vs.emplace_back (move (temp)); } if (!s.empty () && s.back () == delim) vs.push_back ({}); }
Hash
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 unordered_map<string, int > dict; dict.insert (pair<string,int >("apple" ,2 )); dict.insert (unordered_map<string, int >::value_type ("orange" ,3 )); dict["banana" ] = 6 ; if (dict.empty ()) cout<<"该字典无元素" <<endl; else cout<<"该字典共有" <<dict.size ()<<"个元素" <<endl; unordered_map<string, int >::iterator iter; for (iter=dict.begin ();iter!=dict.end ();iter++) cout<<iter->first<<ends<<iter->second<<endl; dict.erase ('a' );
queue
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 queue<int > a; priority_queue<int , vector<int >, std::less<int > > maxHeap; priority_queue<int , vector<int >, std::greater<int > > minHeap; int a = maxHeap.top (); maxHeap.pop (); maxHeap.push (); deque<int > a; deque<int > b (a) ; deque<int > a (&n[1 ], &n[4 ]) ; deq.size (); deq.resize (); deq.push_front (const T& x); deq.push_back (const T& x); deq.insert (iterator it, const T& x); deq.pop_front (); deq.pop_back (); deq.front (); deq.back ();
优先队列 priority_queue
头文件#include <queue>
, 可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队。本质是通过大小顶堆这种数据结构实现。
定义
priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆
基本操作:
top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列
pop 弹出队头元素
swap 交换内容
自定义类型用法