首先,先声明一个头文件
然后,创建一个容器L,然后用迭代器去读取里面的数,
for(list<int>::const_iterator it=L.begin();it!=L.end();it++)
{
cout<<*it;
}
有一些迭代器是可以随机访问的,有一些是双向的,根据迭代器的不同而不同,
利用L.push_front(),去前面插入,利用L.push_back,在后面插入,一般的调换位置可以利用L.sort(),默认是升序,要改成降序的话,需要传一个布尔函数进去,让第一个>第二个
高级运用
list<Person>L
创建一个类
class Person
{
int age;
string name;
int height;
};
void test05()
{
//高级排序
list<Person>L;
Person p1("刘备", 35, 175);
Person p2("关羽", 45, 170);
Person p3("张飞", 40, 180);
Person p4("lzl",25,176);
//插入数据
L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
{
cout << (*it).m_Age << " " << (*it).m_Height << " " << (*it).m_Name << endl;
}
//排序
L.sort(comPare);
cout << "---------------------"<<endl;
for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
{
cout << (*it).m_Age << " " << (*it).m_Height << " " << (*it).m_Name << endl;
}
}