今天主要关于C++中STL常见的几种容器之list容器。此容器是与vector具有相同重要性的一种容器。此两种容器是所以容器中应用最多的。接下来我们来详细讲解一下这个容器吧


(由于和前面容器一样。这里就不多打代码了)这里重点注意下remove这种方法,这种方法其他容器貌似没有.用法为L.remove(1000)
迭代器是可以移动的,link<int>::iteractor it=L.begin();++it;而用it=it+1是错误的,可以利用这种方法结合循环取读取list中间元素

list中数据存储不用【】和at这两种方法,而是用front(取头元素)back(取尾元素)
这里重点要注意list容器中逆序排列要根据sort重新构造函数。
用Person类来进行排序案例
源代码:
#include<iostream>
using namespace std;
#include<list>
#include<string>
class Person
{
public:
Person(string name, int age, int height)
{
m_Name = name;
m_Age = age;
m_Height = height;
}
public:
string m_Name;
int m_Age;
int m_Height;
};
bool compareperson(Person& p1, Person& p2)
{
if (p1.m_Age == p2.m_Age)
{
return p1.m_Height > p2.m_Height;
}
else
{
return p1.m_Age < p2.m_Age;
}
}
void test01()
{
list<Person>L;
Person p1("刘备", 22, 111);
Person p2("关羽", 62, 114);
Person p3("张飞", 52, 116);
Person p4("曹操", 32, 118);
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_Name << endl;
cout << (*it).m_Age << endl;
cout << (*it).m_Height << endl;
}
cout << "............................." << endl;
//排序
L.sort(compareperson);
for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
{
cout << (*it).m_Name << endl;
cout << (*it).m_Age << endl;
cout << (*it).m_Height << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
效果图:

本贴为博主亲手整理。如有错误,请评论区指出,一起进步。谢谢大家的浏览。
529

被折叠的 条评论
为什么被折叠?



