STL对定义的通用容器分三类:顺序性容器、关联式容器和容器适配器。
顺序性容器:vector、deque、list
关联性容器:set、multiset、map、multimap
容器适配器:stack、queue
这里主要学习顺序容器和容器适配器
向量容器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//【例13.5】的程序:向量容器的使用 #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> v(3); //定义初始长度为3的整数容器 v[0]=5; //下标0处放置元素5 v[1]=2; //下标1处放置元素2 v.push_back(7); //在尾部插入元素7 vector<int>::iterator first=v.begin(); //让first指向开头元素 vector<int>::iterator last=v.end(); //让last指向尾部元素 while (first!=last) //循环输出所有元素 cout << *first++ << " "; cout << endl; return 1; } |
双端队列容器
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 26 |
//【例13.6】的程序:双端队列容器的使用 #include <iostream> #include <deque> #include <algorithm> using namespace std; void disp(deque<int> &dq); int main() { deque<int> dq; //建立一个双端队列dq dq.push_front(1); //队头插入1 dq.push_back(2); //队尾插入2 dq.push_front(3); //队头插入3 dq.push_back(4); //队尾插入4 disp(dq); dq.pop_front(); //删除队头元素 dq.pop_back(); //删除队尾元素 disp(dq); return 1; } void disp(deque<int> &dq) { deque<int>::iterator iter; for (iter=dq.begin();iter!=dq.end();iter++) cout << *iter << " "; cout << endl; } |
链表容器
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 |
//【例13.7】的程序:链表容器的使用 #include <iostream> #include <list> using namespace std; int main() { list<int> lst; list<int>::iterator i,start,end; lst.push_back(5); lst.push_back(2); lst.push_back(4); lst.push_back(1); lst.push_back(3); lst.push_back(8); lst.push_back(6); lst.push_back(7); cout << "lst: "; for (i=lst.begin();i!=lst.end();i++) cout << *i << " "; cout << endl; i=lst.begin(); start=++lst.begin(); end=--lst.end(); lst.insert(i,start,end); cout << "lst.insert(i,start,end)" << endl; cout << "lst: "; for (i=lst.begin();i!=lst.end();i++) cout << *i << " "; cout << endl; return 1; } |
栈容器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//【例13.8】的程序:栈容器的使用 #include <iostream> #include <stack> using namespace std; int main() { stack<int> st; st.push(1); st.push(2); st.push(3); cout << st.top() << " "; st.pop(); cout << st.top() << " "; st.pop(); st.top() = 7; st.push(4);st.push(5); st.pop() ; while (!st.empty()) //栈不空时输出栈顶元素并退栈 { cout << st.top() << " "; st.pop() ; } cout << endl; return 1; } |
队列容器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//【例13.9】的程序:队列容器的使用 #include <iostream> #include <queue> using namespace std; int main() { queue<int> q; q.push(1); q.push(2); q.push(3); cout << q.front() << " "; q.pop(); cout << q.front() << " "; q.pop(); q.push(4); q.push(5); q.pop(); while (!q.empty()) //队不空时出队 { cout << q.front() << " "; q.pop(); } cout << endl; return 1; } |