首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ STL 容器完整速查手冊:序列/關聯/適配器全接口總結

     編輯:關於C++

容器分類總覽

類別容器底層結構特點
序列容器vector動態數組隨機訪問快,尾部增刪 O(1)
deque分段數組雙端增刪 O(1),隨機訪問快
list雙向鏈表任意位置增刪 O(1),無隨機訪問
關聯容器set/multiset紅黑樹有序、唯一/可重複、查找 O(log n)
map/multimap紅黑樹鍵值對、按鍵有序
unordered_set/map哈希表無序、平均 O(1)
容器適配器stackdeque/listLIFO,默認 deque
queuedeque/listFIFO,默認 deque
priority_queuevector堆,默認大根堆

序列容器通用接口

// 構造
Container c;                    // 默認
Container c(n);                 // n 個值初始化
Container c(n, val);            // n 個 val
Container c(beg, end);          // 範圍構造
Container c = other;            // 拷貝構造

// 容量
c.empty()    c.size()    c.max_size()    c.resize(n, val)

// 迭代器
c.begin()  c.end()  c.rbegin()  c.rend()  c.front()  c.back()

// 修改
c.push_back(val)  c.pop_back()
c.insert(pos, val)  c.insert(pos, n, val)  c.insert(pos, beg, end)
c.erase(pos)  c.erase(beg, end)  c.clear()
c.assign(beg, end)  c.assign(n, val)
c.swap(other)

// vector/deque 專有
c.capacity()  c.reserve(n)  c[i]  c.at(i)

// list 專有
c.push_front(val)  c.pop_front()
c.merge(other)  c.remove(val)  c.remove_if(pred)
c.reverse()  c.sort()  c.unique()
c.splice(pos, other)  c.splice(pos, other, beg, end)

關聯容器通用接口

// 查找
c.find(key)           // 返回迭代器
c.count(key)          // 0/1 或 多重容器計數
c.lower_bound(key)    // 首個 ≥ key
c.upper_bound(key)    // 首個 > key
c.equal_range(key)    // pair

// 修改
c.insert(val)         // pair (set/map)
c.insert(beg, end)    // 範圍插入
c.erase(key)          // 返回刪除計數
c.erase(pos)  c.erase(beg, end)  c.clear()

// 比較函數對象
c.key_comp()   c.value_comp()

// map 專有
c[key]  // 若無則插入值初始化

容器適配器接口

// stack
s.push(val)  s.pop()  s.top()  s.empty()  s.size()

// queue
q.push(val)  q.pop()  q.front()  q.back()  q.empty()  q.size()

// priority_queue
pq.push(val)  pq.pop()  pq.top()  pq.empty()  pq.size()

// 通用
c1 = c2  比較運算符 == != < <= > >=

string 專用接口精選

// 查找 (返回 size_type, npos 表示未找到)
s.find(str/char, pos)  s.rfind(str/char, pos)
s.find_first_of(str/char, pos)  s.find_last_not_of(str/char, pos)

// 修改
s.append(str)  s.push_back(ch)
s.insert(pos, str)  s.erase(pos, len)
s.replace(pos, len, str)  s.assign(str)

// 子串
s.substr(pos, len)

// C 風格互轉
s.c_str()   // 以 \0 結尾,不可修改
s.data()    // 不保證 \0 結尾
s.copy(buf, len, pos)

// 輸入
getline(cin, s)  getline(cin, s, delim)

選型決策樹

  1. 需隨機訪問 → vector / deque
  2. 頻繁中間插刪 → list
  3. 需有序、去重、區間查詢 → set / map
  4. 需可重複鍵 → multiset / multimap
  5. 無序、極致查找速度 → unordered_set / unordered_map (C++11)
  6. 棧/隊列/優先隊列語義 → 適配器
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved