自学内容网 自学内容网

C++之STL—List 链表

双向链表


链表的组成:链表由一系列**结点**组成

结点的组成:一个是存储数据元素的**数据域**,另一个是存储下一个结点地址的**指针域**

STL中的链表是一个双向循环链表

 

构造函数

List 赋值和交换

 

 容器大小操作


- 判断是否为空   --- empty
- 返回元素个数   --- size
- 重新指定个数   --- resize

 

插入和删除


* 尾插   --- push_back
* 尾删   --- pop_back
* 头插   --- push_front
* 头删   --- pop_front
* 插入   --- insert
* 删除   --- erase
* 移除   --- remove
* 清空   --- clear

数据存取

 list <int > li;

 li.front();        //第一个元素

 li.back();      //最后一个元素

反转和排序

 

自定义排序案例,变量为类class

 

#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("刘备", 35 , 175);
Person p2("曹操", 45 , 180);
Person p3("孙权", 40 , 170);
Person p4("赵云", 25 , 190);
Person p5("张飞", 35 , 160);
Person p6("关羽", 35 , 200);

L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
L.push_back(p5);
L.push_back(p6);

for (list<Person>::iterator it = L.begin(); it != L.end(); it++) {
cout << "姓名: " << it->m_Name << " 年龄: " << it->m_Age 
              << " 身高: " << it->m_Height << endl;
}

cout << "---------------------------------" << endl;
L.sort(ComparePerson); //排序

for (list<Person>::iterator it = L.begin(); it != L.end(); it++) {
cout << "姓名: " << it->m_Name << " 年龄: " << it->m_Age 
              << " 身高: " << it->m_Height << endl;
}
}

int main() {

test01();

system("pause");

return 0;
}

原文地址:https://blog.csdn.net/QoQ_____________/article/details/142493616

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!