STL:List模拟实现

原理:list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。 

优点:任意位置的插入删除效率很高(双向迭代)

缺点:任意位置的随机访问效率很低

list的使用

#include 
#include 
void test1()
{
	std::list l1(3, 10);
	std::list::iterator it = l1.begin();
        //迭代器遍历
	while (it != l1.end()) {
		std::cout << *it << " ";
		++it;
	}
	std::cout << std::endl;
        //(c++11)范围for
	for (auto e : l1) {
		std::cout << e << " ";
	}
	std::cout << std::endl;
}
void test2()
{
	int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
	std::list l(array, array + sizeof(array) / sizeof(array[0]));
	// 使用正向迭代器正向list中的元素
	for (std::list::iterator it = l.begin(); it != l.end(); ++it)
		std::cout << *it << " ";
	std::cout << std::endl;
	// 使用反向迭代器逆向打印list中的元素
	for (std::list::reverse_iterator it = l.rbegin(); it != l.rend(); ++it)
		std::cout << *it << " ";
	std::cout << std::endl;
	// cosnt的正向迭代器
		auto cit = l.cbegin();
	std::cout << typeid(cit).name() << std::endl;
	//*cit = 10; 此行代码编译失败,因为cit为const_iterator类型的迭代器
}
void test3()
{
        //定义一个空list
	std::list l1;
        //使用push_back进行尾插
	l1.p

你可能感兴趣的:(C++)