C++PrimerPlus(第6版)中文版:Chapter16.4泛型编程_概念_容器种类_Example16.12list.cpp

本文详细介绍了C++标准库中的list容器使用方法,涉及构造、遍历、插入、删除、排序等操作,通过实例展示了如何利用list实现数据结构管理和算法应用。

本小节主要讲述容器list的使用方法。详情请看源代码

list.cpp

// Example16.12list.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <list>
#include <iterator>
#include <vector>
#include <algorithm>
void outint(int n) { std::cout << n << " "; }

int main()
{
   // std::cout << "Hello World!\n";
	using namespace std;
	list<int> one(5, 2);//创建了5个 2 
	     for_each(one.begin(),one.end(),outint);//输出了 5个  2
		 cout << endl;
	int stuff[5] = { 1,2,4,8,6 };
    list<int> two;
    two.insert(two.begin(),stuff,stuff+5);//在two的begin处 添加stuff 区间的数值
	     for_each(two.begin(), two.end(), outint);
		 cout << endl;
	 int more[6] = { 6,4,2,4,6,5 };
	 list<int> three(two);//用two 初始化了three,此时three就是two 内容为:1,2,4,8,6
	 three.insert(three.end(),more,more+6);
	     for_each(three.begin(), three.end(), outint);
	     cout << endl; //输出 1 2 4 8 6 6 4 2 4 6 5
	 three.remove(2);//删除three中的所有的  2 
		 for_each(three.begin(), three.end(), outint);
		 cout << endl; //输出  1 4 8 6 6 4 4 6 5
	 three.splice(three.begin(),one);//将链表one的内容插入到three的开始,one的内容是2 2 2 2 2
		 for_each(three.begin(), three.end(), outint);
		 cout << endl; //输出  2 2 2 2 2 1 4 8 6 6 4 4 6 5
	 three.unique();
	    cout << "List three after unique()" << endl;
		for_each(three.begin(), three.end(), outint);
		cout << endl;//输出2 1 4 8 6 4 6 5

	 three.sort();//用运算符< 进行排序
	 three.unique();//将连续的相同的元素压缩为单个元素。复杂度为线性时间
		cout << "List three after sort()and unique()" << endl;
		for_each(three.begin(), three.end(), outint);
		cout << endl;//这是没有调用unique()的时候输出 1 2 4 4 5 6 6 8,调用unique()之后输出:1 2 4 5 6 8
	 two.sort();
	   cout << "List two after sort()" << endl;
	   for_each(two.begin(), two.end(), outint);
	   cout << endl;
	 three.merge(two);//将链表three和two进行合并,合并之前必须排序。
		cout << "Sorted two merged into three" << endl;
		for_each(three.begin(), three.end(), outint);
		cout << endl;//
return 0;
}


运行结果:

2 2 2 2 2
1 2 4 8 6
1 2 4 8 6 6 4 2 4 6 5
1 4 8 6 6 4 4 6 5
2 2 2 2 2 1 4 8 6 6 4 4 6 5
List three after unique()
2 1 4 8 6 4 6 5
List three after sort()and unique()
1 2 4 5 6 8
List two after sort()
1 2 4 6 8
Sorted two merged into three
1 1 2 2 4 4 5 6 6 8 8

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值