C++基础13:容器适配器(Container Adapte)

    技术2025-04-07  12

    1 简介

    容器模板特点容器模板特点栈容器stack后进先出(LIFO)队列容器queue先进先出(FIFO)优先级队列容器priority_queue最高优先级元素先出

    2 栈容器

    2.1 常见用法

    (1)入栈操作(for循环次数)

    for(int i = 0; i<10;++i){ s.push(i); //a1.入栈操作(for循环次数) }

    (2)出栈操作 ,a. while循环判空;b.只能打印头部

    while(!s.empty()){ cout << s.top() << "\t"; s.pop(); //a2.出栈操作 ,while循环判空; }

    (3)不能进行的操作:(栈和vector,list之间的转化) b1.不能随机访问s[] b2.不能使用迭 stack::iterator it = s.begin(); b3.不能使用 for(auto m:s){}进行遍历

    (4)解决之道:将栈转化为顺序容器(vector,list,dequeue) c1.强制类型转化符号vector---->stack

    vector<int> vec ={1,2,3,4,5}; stack<int,vector<int>> s1(vec); //c1强制类型转化符号vector---->stack

    c2.采用push_back加pop()的做法,实现了逆序打印

    vector<int> res; while(!s1.empty()){ res.push_back(s1.top()); //c2.采用push_back加pop()的做法,实现了逆序打印 s1.pop(); } for(auto m:res){ //c3.vector cout << m << "\t" ; } 完整案例 #include <iostream> #include <stack> #include <vector> using namespace std; int main() { stack<int> s; for(int i = 0; i<10;++i){ s.push(i); //a1.入栈操作(for循环次数) } cout << s.size() << endl;; while(!s.empty()){ cout << s.top() << "\t"; s.pop(); //a2.出栈操作 ,while循环判空; } cout << endl; cout << s.size() << endl; // b不能进行的操作: //b1.不能随机访问s[] //b2.不能使用迭代器 //stack<int>::iterator it = s.begin(); //b3.不能使用 for(auto m:s){}进行遍历 //c.解决之道:将栈转化为顺序容器(vector,list,dequeue) vector<int> vec ={1,2,3,4,5}; stack<int,vector<int>> s1(vec); //c1强制类型转化符号vector---->stack vector<int> res; while(!s1.empty()){ res.push_back(s1.top()); //c2.采用push_back加pop()的做法,实现了逆序打印 s1.pop(); } for(auto m:res){ //c3.vector cout << m << "\t" ; } cout << endl; return 0; }

    2.2 面试题

    2.2.1 (面试题24)翻转链表

    翻转链表

    3 队列容器

    3.1 常见用法

    (1) 入队操作

    for(int i = 0; i<10;++i){ q.push(i); //a1.入队操作(for循环次数) }

    (2) 出队操作 ,while循环判空; ,可以打印首尾

    while(!q.empty()){ cout << q.front() << "\t" << q.back()<<endl; q.pop(); //a2.出队操作 ,while循环判空; ,可以打印首尾 }

    (3)队列和容器(list,vector)的转化 b不能进行的操作: //b1.不能随机访问s[] //b2.不能使用迭代器 //queue::iterator it = s.begin(); //b3.不能使用 for(auto m:s){}进行遍历

    //c.解决之道:将栈转化为顺序容器(list,dequeue)

    list<int> l ={1,2,3,4,5}; queue<int,list<int>> q1(l); //c1强制类型转化符号list---->queue

    (4)出队

    while(!q1.empty()){ cout << q1.front() << "\t" << q1.back()<<endl; q1.pop(); //a2.出栈操作 ,while循环判空; } 完整案例 #include <iostream> #include <queue> #include <list> using namespace std; int main() { queue<int> q; for(int i = 0; i<10;++i){ q.push(i); //a1.入队操作(for循环次数) } cout << q.size() << endl;; while(!q.empty()){ cout << q.front() << "\t" << q.back()<<endl; q.pop(); //a2.出队操作 ,while循环判空; ,可以打印首尾 } cout << endl; cout << q.size() << endl; // b不能进行的操作: //b1.不能随机访问s[] //b2.不能使用迭代器 //queue<int>::iterator it = s.begin(); //b3.不能使用 for(auto m:s){}进行遍历 //c.解决之道:将队列转化为顺序容器(list,dequeue,vector) list<int> l ={1,2,3,4,5}; queue<int,list<int>> q1(l); //c1强制类型转化符号list---->queue while(!q1.empty()){ cout << q1.front() << "\t" << q1.back()<<endl; q1.pop(); //a2.出栈操作 ,while循环判空; } cout << endl; return 0; }
    Processed: 0.013, SQL: 9