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

被折叠的 条评论
为什么被折叠?



