1.stack
#include <iostream>
using namespace std;
#include <stack>
void test01()
{
stack<int>s;
s.push(10);
s.push(20);
s.push(30);
s.push(40);
//栈不为空,查看栈顶,执行出栈操作
while (!s.empty())
{
//查看栈顶元素
cout << s.top() << endl;
s.pop();
}
cout << s.size() << endl;
}
int main()
{
test01();
}
2.queue
#include <iostream>
using namespace std;
#include <queue>
class Person
{
public:
Person(string name, int age)
{
this->age = age;
this->name = name;
}
int age;
string name;
};
void test01()
{
queue<Person> q;
Person p1("张三", 18);
Person p2("李四", 20);
Person p3("王五", 22);
q.push(p1);
q.push(p2);
q.push(p3);
while (!q.empty())
{
cout << "队头" << q.front().age << endl;
cout << "队尾" << q.back().age << endl;
q.pop();
}
cout << q.size() << endl;
}
int main()
{
test01();
}
3.list
STL中链表是双向循环链表
1)构造函数
#include <iostream>
using namespace std;
#include <list>
void printList(const list<int>& L)
{
for (list<int>::const_iterator it=L.begin();it!=L.end();it++)
{
cout << *it << endl;
}
cout << endl;
}
void test01()
{
list<int>L1;
L1.push_back(10);
L1.push_back(20);
L1.push_back(30);
L1.push_back(40);
list<int>L2(L1.begin(), L1.end());
//遍历容器
printList(L2);
list<int>L3(L2);
printList(L3);
list<int>L4(10, 100);
printList(L4);
}
int main()
{
test01();
}
2)赋值和交换
#include <iostream>
using namespace std;
#include <list>
void printList(const list<int>& L)
{
for (list<int>::const_iterator it=L.begin();it!=L.end();it++)
{
cout << *it << " ";
}
cout << endl;
}
void test01()
{
list<int>L1;
L1.push_back(10);
L1.push_back(20);
L1.push_back(30);
L1.push_back(40);
L1.push_back(50);
list<int>L2;
L2.assign(L1.begin(), L1.end());
printList(L2);
list<int>L3;
L3.assign(10,100);
printList(L3);
list<int>L4;
L4 = L3;
printList(L4);
L4.swap(L1);
printList(L4);
}
int main()
{
test01();
}
3)大小操作
操作同vector
4)插入删除
#include <iostream>
using namespace std;
#include <list>
void printList(const list<int>& L)
{
for (list<int>::const_iterator it=L.begin();it!=L.end();it++)
{
cout << *it << " ";
}
cout << endl;
}
void test01()
{
list<int>L1;
L1.push_back(10);
L1.push_back(20);
L1.push_back(30);
L1.push_back(40);
L1.push_back(50);
L1.pop_back();
L1.pop_front();
printList(L1);
//只支持++,--
list<int>::iterator it=L1.begin();
L1.insert(it++, 10);
it = L1.begin();
L1.erase(it);
printList(L1);
//删除所有20
L1.remove(20);
printList(L1);
L1.clear();
printList(L1);
}
int main()
{
test01();
}
5.数据存取
迭代器不能随机访问
访问中间元素需要自己写函数
6.反转和排序
#include <iostream>
using namespace std;
#include <list>
void printList(const list<int>& L)
{
for (list<int>::const_iterator it=L.begin();it!=L.end();it++)
{
cout << *it << " ";
}
cout << endl;
}
void test01()
{
list<int>L1;
L1.push_back(20);
L1.push_back(10);
L1.push_back(30);
L1.push_back(40);
L1.push_back(50);
printList(L1);
//反转
L1.reverse();
printList(L1);
//排序
L1.sort();
printList(L1);
//所有不支持随机访问迭代器的容器,不可以使用标准算法
//内部会提供一些算法
//sort(L1.begin(),L1..end());
}
int main()
{
test01();
}