示例中的代码使用std::list<type>name(first,last)方法创建了元素在指定范围内的链表,first代表起始范围,last代表结束范围,具体的实现代码:
std::cout << "使用未排序存储0-9的数组初始化list1
" << endl;
int array[10] = {1,3,5,7,8,9,2,4,6,0};
list<int> list1(array,array+10);//此时传入list1()方法的参数是两个指针,指针范围是[array,array+10)。所以上面所说的范围是段地址范围,对应数组下标范围[0,10)。
代码:
#include <iostream>
#include <list>
#include <vector>
using std::vector;
using std::list;
using std::cout;
using std::endl;
#include <list>
#include <vector>
using std::vector;
using std::list;
using std::cout;
using std::endl;
int main()
{
std::cout << "使用未排序存储0-9的数组初始化list1 " << endl;
int array[10] = {1,3,5,7,8,9,2,4,6,0};
std::cout << *(array+9) << endl;
list<int> list1(array,array+10);
std::cout << list1.size() << ' ';
std::cout << "list1调用sort方法排序 " <<endl;
list1.sort();
list<int>::iterator iter = list1.begin();
std::cout << *iter << " ";
std::cout << "通过迭代器访问list双向链表中从头开始向后的第四个元素 " << endl;
for(int i = 0;i<3;i++)
{
iter++;
}
std::cout << *iter <<" ";
std::cout <<*( list1.end()) << ' ';
list1.insert(list1.end(),13);
std::cout << "在末尾插入数字13 " << endl;
for(auto it = list1.begin();it != list1.end();it++)
{
std::cout << " " << *it <<" ";
}
}
{
std::cout << "使用未排序存储0-9的数组初始化list1 " << endl;
int array[10] = {1,3,5,7,8,9,2,4,6,0};
std::cout << *(array+9) << endl;
list<int> list1(array,array+10);
std::cout << list1.size() << ' ';
std::cout << "list1调用sort方法排序 " <<endl;
list1.sort();
list<int>::iterator iter = list1.begin();
std::cout << *iter << " ";
std::cout << "通过迭代器访问list双向链表中从头开始向后的第四个元素 " << endl;
for(int i = 0;i<3;i++)
{
iter++;
}
std::cout << *iter <<" ";
std::cout <<*( list1.end()) << ' ';
list1.insert(list1.end(),13);
std::cout << "在末尾插入数字13 " << endl;
for(auto it = list1.begin();it != list1.end();it++)
{
std::cout << " " << *it <<" ";
}
}
结果: