C Primer Plus书中代码注释-chapter16_12_list.cpp

chapter16_12_list.cpp

#include <iostream>
#include <list>
#include <iterator>
#include <algorithm> 

void outint(int n)
{
	std::cout << n << " ";
}

int main()
{
	using namespace std;
	list<int> one(5, 2);		//新建int类型list ,初始list大小为5,值全为2 
	int stuff[5] = {1, 2, 4, 8, 6};		//初始int类型数组stuff 
	list<int> two;				//新建int类型list 
	two.insert(two.begin(), stuff, stuff + 5);	//把数组stuff的数据传到容器two的起始位置 
	int more[6] = {6, 4, 2, 4, 6, 5};			//初始int类型数组more 
	list<int> three(two);						//用容器two的数据初始化列表three 
	three.insert(three.end(), more, more + 6);	//把more数组的数据插入到容器three的末尾  
	
	cout << "List one: ";
	for_each(one.begin(), one.end(), outint);	//隐式迭代器遍历one的元素,并把迭代器作为参数传给outint 
	cout << endl << "List two: ";
	for_each(two.begin(), two.end(), outint);
	cout << endl << "List three: ";
	for_each(three.begin(), three.end(), outint);
	three.remove(2);							//从列表容器three中删除元素2 
	cout << endl << "List three minus 2s: ";
	for_each(three.begin(), three.end(), outint);
	three.splice(three.begin(), one);			//将链表one的内容插入到链表three起始位置的前面,并清除链表one的数据 
	cout << endl << "List three after splice: ";
	for_each(three.begin(), three.end(), outint);
	cout << endl << "List one: ";				
	for_each(one.begin(), one.end(), outint);	//这里什么都没有显示,因为链表one的数据已经被移动到了链表three里面
	three.unique();								//将连续的相同元素压缩为单个元素 
	cout << endl << "List three after unique: ";
	for_each(three.begin(), three.end(), outint);
	three.sort();								//把链表three中的元素按从小到大进行排序 
	
	three.unique();								//将“连续的”相同元素压缩为单个元素			
	cout << endl << "List three after sort & unique: ";
	for_each(three.begin(), three.end(), outint);
	two.sort();									//将链表two的元素进行排序,因为merge需要被合并的链表必须为已经排序的
	three.merge(two);							//将两个链表合并,并自动排序保存到链表three中 
	cout << endl << "Sorted two merged into three: ";
	for_each(three.begin(), three.end(), outint);
	cout << endl;
	
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/xiaoyami/article/details/107664624
今日推荐