
C++ 第十三章第十四章 案例教程说明:本教程承接前十二章。第十三章聚焦STL进阶(容器适配器、优先级队列、算法复杂度、仿函数、无序容器),第十四章讲解多线程编程(thread、mutex、async、future、atomic)。通过“任务调度系统”和“并行计算器”实战串联所有知识点。第一部分:第十三章 STL进阶一、背景故事:小杨需要优先级队列和更高效的查找小杨的图形绘制系统运行良好,但他希望实现一个任务队列:根据任务优先级,总是执行最重要的任务。同时,他需要快速在海量数据中查找元素,希望使用哈希表(unordered_map)。于是他开始深入学习STL的高级组件。二、容器适配器容器适配器是基于底层容器(如deque、vector、list)实现的特殊接口。2.1 stack(栈)后进先出(LIFO)。默认基于deque。#includestackstackints;s.push(1);s.push(2);s.pop();// 弹出2inttop=s.top();// 12.2 queue(队列)先进先出(FIFO)。默认基于deque。#includequeuequeueintq;q.push(1);q.push(2);q.pop();// 弹出1intfront=q.front();// 22.3 priority_queue(优先队列)最大值总是在顶部,默认使用比较(最大堆)。#includequeuepriority_queueintpq;// 最大堆pq.push(3);pq.push(1);pq.push(4);coutpq.top()endl;// 4pq.pop();// 最小堆priority_queueint,vectorint,greaterintminHeap;minHeap.push(3);minHeap.push(1);minHeap.push(4);coutminHeap.top()endl;// 1自定义比较仿函数:structTask{intpriority;string name;// 自定义比较:优先级高的在堆顶(注意是 less 逻辑)booloperator(constTaskother)const{returnpriorityother.priority;// 最大堆需要这样写}};priority_queueTasktaskQueue;taskQueue.push({3,"写报告"});taskQueue.push({1,"回复邮件"});taskQueue.push({5,"修复bug"});couttaskQueue.top().nameendl;// 修复bug三、无序关联容器(哈希表)C++11 提供了基于哈希的容器:unordered_set、unordered_map,平均O(1)查找。#includeunordered_map#includeunordered_setunordered_mapstring,intscores;scores["张三"]=95;scores["李四"]=87;if(scores.find("张三")!=scores.end()){cout"张三分数: "scores["张三"]endl;}unordered_setintnums={1,2,3,4,5};nums.insert(6);nums.erase(3);自定义哈希(为自定义类型):structPoint{intx,y;booloperator==(constPoint