stack容器先进后出,没有迭代器,不支持遍历访问
#include<iostream>
#include<stack>
using namespace std;
void test01()
{
stack<int>s;
stack<int>s1;
s.push(10);
s.push(20);
s.push(30);
s.push(40);
while (!s.empty())
{
cout <<s.top()<<" ";
s.pop();//弹出栈顶元素
}
}
int main()
{
test01();//40 30 20 10
system("pause");
}}
queue容器先进先出不提供迭代器,不能遍历数据
#include<iostream>
#include<queue>
using namespace std;
void test01()
{
queue<int>q;
q.push(10);
q.push(20);
q.push(30);
q.push(40);
while (!q.empty())
{
cout << q.front() << " ";
q.pop();
}
}
int main()
{
test01();//10 20 30 40
system("pause");
}
list容器
list是一个双向循环列表,有迭代器,不支持随机访问it+=3(错)
#include<iostream>
#include<list>
#include<string>
using namespace std;
void print(list<int>&L)
{
for (list<int>::reverse_iterator it = L.rbegin(); it != L.rend(); it++)
{
cout << *it << " ";
}
}
void test01()
{
list<int>l;
for (int i = 0; i < 10; i++)
{
l.push_back(i);
}
print(l);
}
int main()
{
test01();
system("pause");
return 0;
}//9 8 7 6 5 4 3 2 1 0
假如list容器里的数据需要排序,那么不能直接用sort(l.begin(),l.end(),mysort);原因是所有不支持随机访问的迭代器,不可以用系统提供的算法,但是这个类的内部会提供、。l.sort();如果从小到大l.sort(mysort);//回调函数
#include<iostream>
#include<list>
#include<string>
using namespace std;
class person
{
public:
person(string mName, int mNum) : mName(mName), mNum(mNum){};
string mName;
int mNum;
};
bool mysort(person&p1, person&p2)
{
if (p1.mNum > p2.mNum)
{
return true;
}
else
return false;
}
void printData(list<person>&p)
{
for (list<person>::iterator it = p.begin(); it != p.end(); it++)
{
cout << "姓名:" << it->mName << "学号:" << it->mNum << endl;
}
}
void test01()
{
list<person>p;
person p1("wang", 12);
person p2("yang", 12);
person p3("ge", 10);
person p4("sun", 17);
p.push_back(p1);
p.push_back(p2);
p.push_back(p3);
p.push_back(p4);
p.sort(mysort);
printData(p);
}
int main()
{
test01();
system("pause");
return 0;
}
#include<iostream>
#include<list>
#include<string>
using namespace std;
class person
{
public:
person(string mName, int mNum) : mName(mName), mNum(mNum){};
string mName;
int mNum;
//重载==让remove可以删除自定义的person类型
bool operator == (const person&p)
{
if (p.mName == this->mName&&p.mNum == this->mNum)
{
return true;
}
else
return false;
}
};
void printData(list<person>&p)
{
for (list<person>::iterator it = p.begin(); it != p.end(); it++)
{
cout << "姓名:" << it->mName << "学号:" << it->mNum << endl;
}
}
void test01()
{
list<person>p;
person p1("wang", 12);
person p2("yang", 12);
person p3("ge", 10);
person p4("sun", 17);
p.push_back(p1);
p.push_back(p2);
p.push_back(p3);
p.push_back(p4);
printData(p);
cout << "删除后的数据————————————————————" << endl;
p.remove(p1);//remove可以删除默认的数据,
//但是不可以删除自定义数据
printData(p);
}
int main()
{
test01();
system("pause");
return 0;
}