1.list基本用法
#include<iostream>
#include<list>
using namespace std;
void PrintList(list<int>&l){
for(list<int>::const_iterator it=l.begin();it!=l.end();it++){
cout<<*it<<" ";
}
cout<<endl;
}
bool MyCompare(int v1,int v2){
return v1>v2;
}
int main(){
list<int>l;
l.push_back(10);
l.push_back(20);
l.push_back(30);
//list的迭代器不能+1 只能++或者--
list<int>l2(l.begin(),--l.end()); //10 20
list<int>l3;
//assign()赋值函数 包括assign(begin,end)和assign(n,elem)
l3.assign(++l2.begin(),l2.end()); //20
list<int>l4;
l4.assign(5,100);
PrintList(l3);
PrintList(l4);
//resize()函数调整链表长度 若变长则按照默认值填充,变短则删除
//(resize(n))/resize(n,elem)
l4.resize(10,200);
PrintList(l4);
//插入 insert(pos,elem) insert(pos,n,elem) insert(begin,end)
auto pos = l2.begin();
pos++;
l2.insert(pos,5);
l2.insert(pos,4,200);
PrintList(l2);
//删除 erase(begin,end) erase(pos)
l2.erase(l2.begin());
PrintList(l2);
//指定元素移除 remove(elem)
l2.remove(200);
PrintList(l2);
//反转
l2.reverse();
PrintList(l2);
//排序 升序 降序
l2.sort();
PrintList(l2);
//降序
l2.sort(MyCompare);
PrintList(l2);
}
2.自定义数据类型
#include<iostream>
#include<list>
using namespace std;
class Person{
public:
string name;
int age;
int height;
Person(string name,int age,int height):name(name),age(age),height(height){
}
};
bool MyCompare(Person p1,Person p2){
if(p1.age!=p2.age){
return p1.age<p2.age;
}else{
return p1.height>p2.height;
}
}
void PrintList(list<Person>&l){
for(list<Person>::iterator it=l.begin();it!=l.end();it++){
cout<<it->name<<" "<<it->age<<" "<<it->height<<endl;
}
}
int main(){
list<Person>l;
Person p1("yzq",18,180);
Person p2("yzq",20,181);
Person p3("yzq",20,175);
Person p4("yxc",8,199);
l.push_back(p1);
l.push_back(p2);
l.push_back(p3);
l.push_back(p4);
PrintList(l);
cout<<"------------"<<endl;
l.sort(MyCompare);
PrintList(l);
}