栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ list容器

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ list容器

#include 
#include 
#include "myList.hpp"
using namespace std;

//基本操作
void testList()
{
	list mylist;
	for (int i = 0; i < 3; i++)
	{
		mylist.push_front(i);		//插入
		//0   1 0   2 1 0
	}
	mylist.push_back(101);
	cout << mylist.front() << endl;
	cout << mylist.back() << endl;
	cout << mylist.size() << endl;
	//遍历 
	for (auto v : mylist)
	{
		cout << v << "t";
	}
	cout << endl;
	//迭代器
	list::iterator iter;
	for (iter = mylist.begin(); iter != mylist.end(); iter++)
	{
		cout << *iter << "t";
	}
	cout << endl;
	mylist.sort();		//排序
	for (auto v : mylist)
	{
		cout << v << "t";
	}
	cout << endl;
	mylist.reverse();	//反转
	//删除的方式进行遍历
	//pop_back()
	//pop_front();
	while (!mylist.empty())
	{
		cout << mylist.front() << "t";
		mylist.pop_front();
	}
	cout << mylist.size() << endl;
}
class MM 
{
public:
	MM(string name, int age) :name(name), age(age) {}
	string getName() const { return name; }
	int getAge()	const { return age; }
protected:
	string name;
	int age;
};
//直接用子函数的方式描述比较准则
bool comparentByName(const MM& object1, const MM& object2)
{
	return object1.getName() < object2.getName();
}
bool comparentByAge(const MM& object1, const MM& object2) 
{
	return object1.getAge() > object2.getAge();
}
//操作自定义类型
void testListData() 
{
	list mmList;
	MM mm[3] = { {"string1",15},
	{"string2",17},
	{"string0",29} };
	for (int i = 0; i < 3; i++) 
	{
		mmList.push_back(mm[i]);
	}
	for (auto v : mmList) 
	{
		cout << v.getName() << "t" << v.getAge() << endl;
	}
	cout << "---------------------" << endl;
	mmList.sort(comparentByName);
	for (auto v : mmList)
	{
		cout << v.getName() << "t" << v.getAge() << endl;
	}
	cout << "---------------------" << endl;
	mmList.sort(comparentByAge);
	for (auto v : mmList)
	{
		cout << v.getName() << "t" << v.getAge() << endl;
	}

}
void testMyList()
{
	MyList mylist;
	for (int i = 0; i < 3; i++)
	{
		mylist.push_front(i);		//插入
		//0   1 0   2 1 0
	}
	mylist.push_back(101);
	cout << mylist.front() << endl;
	cout << mylist.back() << endl;
	cout << mylist.size() << endl;
	//遍历 
	for (auto v : mylist)
	{
		cout << v << "t";
	}
	cout << endl;
}

int main() 
{
	testListData();
	testMyList();
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/396406.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号