#include"stdafx.h"
#include<list>
#include<iostream>
using namespace std;
typedef struct {
int number;
bool sex;
char name[20];
}Student;
list <Student> cl; //链表中的元素为 STUDENT结构类型
list <Student>::iterator cl_Iter; //为链表申明一个迭代器 用来遍历此链表
void PrintData()
{
//获取头结点 用一个迭代器来遍历链表
cl_Iter = cl.begin();
//遍历所有结点
for (cl_Iter; cl_Iter != cl.end(); cl_Iter++)
{
//cl_Iter指针 指向给定的结构体
cout << "当前结点数据" << "学号 " << cl_Iter->number << " 性别 " << (cl_Iter->sex?"男":"女" )<< " 名字 "<< cl_Iter->name << endl;
}
}
void Delete(int number)
{
//获取头结点 用一个迭代器来遍历链表
cl_Iter = cl.begin();
//遍历所有结点
for (cl_Iter; cl_Iter != cl.end(); cl_Iter++)
{
//如果结点数据等于要删除的数据 调用删除函数
if (number == cl_Iter->number)
{
cl.erase(cl_Iter);
break;
}
}
}
//通过学号排序
bool SoftBynumber(Student &s1,Student &s2)
{
return s1.number < s2.number;
}
int main(int argc, char* argv[])
{
//向链表头部添加数据
Student Student1 = { 5, 0, "张三" };
Student Student2 = { 9, 0, "李四" };
Student Student3 = { 4, 1, "王英" };
cl.push_front(Student1);
cl.push_front(Student2);
cl.push_front(Student3);
PrintData();
//排序
cl.sort(SoftBynumber);
cout << "******* 排序后的数据为 *******" << endl;
PrintData();
/* 删除指定结点的数据 */
Delete(5);
cout << "******* 删除后的数据为 *******"<< endl;
PrintData();
getchar();
return 0;
}
c++ STL模板库 list的使用
最新推荐文章于 2023-03-17 17:30:06 发布