一些函数的使用方法:
1. 函数名: merge(list<T, Alloc>& x)
功能:将作为参数的list与调用该函数的list进行合并,并对他们进行升序排列,操作之后x为空
2.函数名: splice(iterator pos, list<T, Alloc>x)
功能: 将x的内容插入到调用list中的pos位置的前面, 操作之后x为空
3.函数名: unique();
功能: 将调用list中重复的元素进行合并
4.函数名:swap(list<type> list);
功能:将调用list的内容与参数list的内容交换
5.函数名:insert(iterator pos, type value);
功能:将value值插入到调用list的pos位置之前
6.函数名:insert(iterator pos, int count, type value);
功能:将两个值同为value的元素插入到调用list的pos位置之前
7.函数名:insert(iterator pos, iterator pos1, iterator pos2);
功能:将某个list中从pos1到pos2的内容插入到调用list的pos位置之前
示例代码:
#include <iostream>
#include <list>
using namespace std;
int show_elements(list<int> lt)
{
list<int>::iterator ite;
if(lt.size() == 0)
{
cout << "空" <<endl;
return 0;
}
for(ite = lt.begin(); ite != lt.end(); ite ++)
cout << *ite << " ";
cout << endl;
return 0;
}
int main()
{
list<int> list_1;
list<int> list_2;
list<int> list_3;
int i = 0;
for(i = 0; i < 8; i ++) //给list_1赋初值
list_1.push_back(i);
cout << "list_1中的元素为 : ";
show_elements(list_1);
for(i = 5; i < 12; i ++) //给list_2赋初值
list_2.push_back(i);
cout << "list_2中的元素为 : ";
show_elements(list_2);
for(i = 10; i < 15; i ++) //给list_3赋初值
list_3.push_back(i);
cout << "list_3中的元素为 : ";
show_elements(list_3);
list_1.swap(list_2); //对换两个list中的元素
cout << "After swap list_1 and list_2 : " << endl;
cout << "list_1中的元素为 : ";
show_elements(list_1);
cout << "list_2中的元素为 : ";
show_elements(list_2);
list_1.insert(list_1.begin(), -1); //将-1插入到list_1的头部
cout << "After insert one element in the front of list_1 :" << endl;
cout << "list_1 is : ";
show_elements(list_1);
list_1.insert(list_1.end(), 2, -8); //将两个-8数插入到list_1的尾部
cout << "After insert two elements in the end of list_1 :" << endl;
cout << "list_1 is : ";
show_elements(list_1);
list_1.insert(list_1.begin(), list_2.begin(), list_2.end()); //将list_2中的元素插入到list_1的头部
cout << "After insert list_2's elements in the front of list_1 : " << endl;
cout << "list_1 is ";
show_elements(list_1);
cout << "list_2 is ";
show_elements(list_2);
list_1.merge(list_2); //合并两个list,合并后list_2为空
cout << "After merge list_1 and list_2: " << endl;
cout << "list_1 中的元素为 : ";
show_elements(list_1);
cout << "list_2中的元素为 : ";
show_elements(list_2);
list_1.splice(list_1.begin(), list_3); //将list_2插入到list_1指定的位置的前面
cout << "After splice list_1 and list_3" << endl;
cout << "list_1 中的元素为 : ";
show_elements(list_1);
cout << "list_3中的元素为 : ";
show_elements(list_3);
list_1.unique( ); //去掉list_1中重复的元素
cout << "After unique, list_1中的元素为 : ";
show_elements(list_1);
return 0;
}
执行结果: