list
list构造
赋值和交换
大小操作
插入和删除
list数据存取
只能迭代器++,或者–;
迭代器+=2;//错误;
迭代器+=1;//错误;没有重载+
迭代器++;//正确;
反转和排序
sort默认是从小到大;
从大到小代码:
#include<iostream>
#include <list>
#include <algorithm>
bool mycompare(int a,int b)
{
return a > b;
}
using namespace std;
int main()
{
list <int >l;
l.push_back(10);
l.push_back(20);
l.push_back(40);
l.push_back(30);
l.sort(mycompare);
for (list<int>::iterator it = l.begin(); it != l.end(); it++)
{
cout << *it << endl;
}
}
进阶:将自定义数据类型进行排序,person排序规则:按照身高排序,身高如果相同则按照年龄从大到小排序
#include <iostream>
#include <list>
#include <algorithm>
#include<string>
using namespace std;
//按照身高排序,身高如果相同则按照年龄从大到小排序
using namespace std;
class person
{
public:
person(string s1,int year, int len)
{
this->name = s1;
this->len = len;
this->year = year;
}
string name;
int year;
int len;
};
bool cmp(person p1,person p2)
{
if(p1.year !=p2.year )
return p1.year>p2.year;
else
{
return p1.len >p2.len ;
}
}
int main()
{
person p1("刘备", 35, 175);
person p2("曹操", 45, 180);
person p3("孙权", 40, 180);
person p4("赵云", 35, 180);
list<person>a;
a.push_back(p1);
a.push_back(p2);
a.push_back(p3);
a.push_back(p4);
for (list<person>::iterator it = a.begin();it != a.end(); it++)
{
cout << "姓名 " << (*it).name << " 年龄是 " << it->year << " 身高是 " << it->len << endl;
}
cout<<"-----------------------------------------------"<<endl;
//排序返回的是一个bool类型
a.sort(cmp) ;
for (list<person>::iterator it = a.begin();it != a.end(); it++)
{
cout << "姓名 " << (*it).name << " 年龄是 " << it->year << " 身高是 " << it->len << endl;
}
}