zl程序教程

您现在的位置是:首页 >  其他

当前栏目

CPP 做算法题时常用的容器技巧

2023-03-07 09:49:38 时间

整理了一下 CPP 做算法题时常用的容器技巧。遇到一门新语言时,我首先都会思考如何实现下属功能。关于算法的笔记放在 GitHub[1] 上。

定长数组

  • 数组

变长数组

  • vector

哈希表

  • 有序字典

优先队列

  • 优先队列重载

排序

  • 排序返回索引

定长数组

要求:

  • 声明与取数

数组

  1. int dx[4] = {0, 1, 0, -1}; 
  2. int a[N]; 
  3.  
  4. dx[0]; 

变长数组

要求:

  • 取值:取头取尾取索引
  • 追加
  • 掐头去尾

vector

  1. vector<int> ans(n);  // 初始长度 n ,默认值为 0 
  2.  
  3. // 取值:取头取尾取索引 
  4. ans.front(); 
  5. ans.back(); 
  6. ans[i] += 1; 
  7.  
  8. // 追加 
  9. // 为什么 std::vector 不支持 push_front? - Milo Yip的回答 - 知乎 
  10. // https://www.zhihu.com/question/51555037/answer/126373709 
  11. ans.push_back(5);  // O(1) 
  12.  
  13. // 去尾 
  14. ans.pop_back(); 

哈希表

要求:

  • 键值已存在
  • 有序字典
  1. map<intint> S; 
  2. // 键值已存在 
  3. if (S.count(5)) 
  4.     // S[5] 被定义过 
  5. else 
  6.     // S[5] 未被定义过 

有序字典

  • map 有序,基于红黑树
  • unordered_map 无序,基于映射,效率可能更高

优先队列

要求:

  • 空尺看存弹
  • 重载存储对象
  • 重载比较函数

  1. // 默认是大根堆 
  2. priority_queue<int> heap; 
  3.  
  4. // 改为小根堆 
  5. priority_queue<int, vetor<int>, greater<int> > min_heap; 
  6.  
  7. // 空尺看存弹 
  8. heap.empty(); 
  9. heap.size(); 
  10. heap.top(); 
  11. heap.push(5); 
  12. heap.pop(); 

优先队列重载

  1. // 重载比较函数 
  2. struct cmp { 
  3.     template<typename T, typename U> 
  4.     bool operator()(T const& left, U const &right) { 
  5.         if (left.second < right.secondreturn true
  6.         return false
  7.     } 
  8. }; 
  9.  
  10. int main() { 
  11.     unordered_map<intint> mp; 
  12.     mp[3] = 4; 
  13.     mp[2] = 44; 
  14.     mp[12] = 432; 
  15.     // 重载存储对象 pair<intint
  16.     priority_queue<pair<intint>, vector<pair<intint>>, cmp>  pq(mp.begin(), mp.end());  //完成pq的初始化 
  17.  
  18. // 版权声明:本文为CSDN博主「leagalhigh」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 
  19. // 原文链接:https://blog.csdn.net/u014257954/article/details/78623215 

排序

要求:

  • 重载排序规则
  • 排序返回索引

  1. vector<int> ans; 
  2. sort(ans.begin(), ans.end());  // 默认从小到大 
  3.  
  4. vector<pair<intint>> res; 
  5. sort(res.begin(), res.begin());  // 默认比较第一个元素 

排序返回索引

  1. vector<int> data = {5, 16, 4, 7};    
  2. vector<intindex(data.size(), 0); 
  3. for (int i = 0 ; i != index.size() ; i++) { 
  4.     index[i] = i; 
  5. sort(index.begin(), index.end(), 
  6.     [&](const int& a, const int& b) { 
  7.         return (data[a] < data[b]); 
  8.     } 
  9. ); 
  10. for (int i = 0 ; i != index.size() ; i++) { 
  11.     cout << index[i] << endl; 
  12. // 版权声明:本文为CSDN博主「liangbaqiang」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 
  13. // 原文链接:https://blog.csdn.net/qq_36523492/article/details/114122256 

参考资料

[1]算法的笔记: https://github.com/PiperLiu/ACMOI_Journey