c++---list

list的介绍和使用
list的模拟实现
list和vector的对比

  1. list的介绍和使用
    list的介绍
  • list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。
  • list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向 其前一个元素和后一个元素。
  • list与forward_list非常相似:最主要的不同在于forward_list是单链表,只能朝前迭代,已让其更简单高 效。
  • 与其他的序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率 更好。
  • 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问,比如:要访问list 的第6个元素,必须从已知的位置(比如头部或者尾部)迭代到该位置,在这段位置上迭代需要线性的时间 开销;list还需要一些额外的空间,以保存每个节点的相关联信息(对于存储类型较小元素的大list来说这 可能是一个重要的因素)
    在这里插入图片描述

list的使用
list的接口比较多,下面列举常用的接口
assign() 给list赋值
back() 返回最后一个元素
begin() 返回指向第一个元素的迭代器
clear() 删除所有元素
empty() 如果list是空的则返回true
end() 返回末尾的迭代器
erase() 删除一个元素
front() 返回第一个元素
get_allocator() 返回list的配置器
insert() 插入一个元素到list中
max_size() 返回list能容纳的最大元素数量
merge() 合并两个list
pop_back() 删除最后一个元素
pop_front() 删除第一个元素
push_back() 在list的末尾添加一个元素
push_front() 在list的头部添加一个元素
rbegin() 返回指向第一个元素的逆向迭代器
remove() 从list删除元素
remove_if() 按指定条件删除元素
rend() 指向list末尾的逆向迭代器
resize() 改变list的大小
reverse() 把list的元素倒转
size() 返回list中的元素个数
sort() 给list排序
splice() 合并两个list
swap() 交换两个list
unique() 删除list中重复的元素

#include <iostream>
#include <string>
#include <list>
 
using namespace std;
 
struct Student
{
    int id;
    string name;
    int score;
};
 
#define func_log(s, s2) do {cout << "[" << s << "] " << s2 << endl;} while (0);
list<Student> Students;
 
void add(Student &obj)
{
    func_log(__func__, "");
    Students.push_back(obj);
}
 
void remove(int id)
{
    func_log(__func__, "");
    list<Student>::iterator it = Students.begin();
    for (it; it != Students.end(); it++)
    {
        if (id == it->id)
        {
            cout << "remove: " << id << endl;
            Students.erase(it);
            break;
        }
    }
 
    func_log(__func__, "end");
}
 
void modify(Student &obj)
{
    func_log(__func__, "");
    list<Student>::iterator it = Students.begin();
    for (it; it != Students.end(); it++)
    {
        if (obj.id == it->id)
        {
            cout << "modify: [id]: " << obj.id << endl;
            cout << "modify: [name]: " << obj.name << endl;
            cout << "modify: [score]: " << obj.score << endl;
            *it = obj;
            break;
        }
    }
    func_log(__func__, "end");
}
 
int search(int id, Student &obj)
{
    func_log(__func__, "begin");
    int result = false;
    list<Student>::iterator it = Students.begin();
    for (it; it != Students.end(); it++)
    {
        if (id == it->id)
        {
            obj = *it;
            cout << "Found: [id]: " << obj.id << endl;
            cout << "Found: [name]: " << obj.name << endl;
            cout << "Found: [score]: " << obj.score << endl;
            result = true;
            break;
        }
    }
 
    func_log(__func__, "end");
    return result;
}
 
void show()
{
    cout << "#####################" << endl;
    list<Student>::iterator it = Students.begin();
    for (it; it != Students.end(); it++)
    {
        cout << it->id << " ";
        cout << it->name << " " ;
        cout << it->score << endl;
    }
    cout << "#####################" << endl;
}
 
int main() {
    Student st1 = {1, "laoyang", 99};
    Student st2 = {2, "laoyanj", 98};
    Student st3 = {3, "laoyanh", 97};
    Student st4 = {4, "laoyani", 96};
    add(st1);
    add(st2);
    add(st3);
    add(st4);
    show();
 
    Student stu;
    if (search(3, stu))
    {
        cout << "search OK" << endl;
        cout << "\tid: " << stu.id << endl;
        cout << "\tname: " << stu.name << endl;
        cout << "\tscore: " << stu.score << endl;
    }
    else
    {
        cout << "search Failed." << endl;
    }
 
    stu.id = 1;
    modify(stu);
    show();
 
    remove(2);
    show();
 
    return 0;
}

这里需要注意的是迭代器

  • begin和end是正向迭代器,对迭代器执行++操作,迭代器向后移动
  • rbegin与rend为反向迭代器,对迭代器执行++操作,迭代器向前移动
 #include <iostream> 
 using namespace std; 
 #include <list>
 
void print_list(const list<int>& l) {    
// 注意这里调用的是list的 begin() const,返回list的const_iterator对象    
	for (list<int>::const_iterator it = l.begin(); it != l.end(); ++it)    {
        cout << *it << " ";        // *it = 10; 编译不通过   
	}     
 cout << endl;
 }
 
int main() {  
  int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };  
  list<int> l(array, array + sizeof(array) / sizeof(array[0]));    // 使用正向迭代器正向list中的元素    
  for (list<int>::iterator it = l.begin(); it != l.end(); ++it)
        cout << *it << " "; 
         cout << endl;
 
    // 使用反向迭代器逆向打印list中的元素    
    for (list<int>::reverse_iterator it = l.rbegin(); it != l.rend(); ++it)        
    	cout << *it << " ";    
    cout << endl;
 
    return 0;
   }

  • 迭代器失效问题
    前面说过,此处大家可将迭代器暂时理解成类似于指针,迭代器失效即迭代器所指向的节点的无效,即该节 点被删除了。因为list的底层结构为带头结点的双向循环链表,因此在list中进行插入时是不会导致list的迭代 器失效的,只有在删除时才会失效,并且失效的只是指向被删除节点的迭代器,其他迭代器不会受到影响

list模拟实现

#pragma once

template<class T>
struct ListNode
{
	ListNode<T>* _next;
	ListNode<T>* _prev;
	T _data;

	ListNode(const T& x = T())
		:_next(nullptr)
		, _prev(nullptr)
		, _data(x)
	{}
};

// typedef __ListIterator<T, T&, T*> iterator;
// typedef __ListIterator<T, const T&, const T*> const_iterator;
template<class T, class Ref, class Ptr>
struct __ListIterator
{
	typedef ListNode<T> Node;
	typedef __ListIterator<T, Ref, Ptr> Self;
	Node* _node;

	__ListIterator(Node* node)
		:_node(node)
	{}

	// *it;
	Ref operator*()
	{
		return _node->_data;
	}

	// it->
	//T* operator->()
	Ptr operator->()
	{
		return &_node->_data;
	}

	Self& operator++()
	{
		_node = _node->_next;
		return *this;
	}

	Self operator++(int)
	{
		Self tmp(*this);
		_node = _node->_next;
		return tmp;
	}


	Self& operator--()
	{
		_node = _node->_prev;
		return *this;
	}

	// it1 != it2
	bool operator!=(const Self& it)
	{
		return _node != it._node;
	}
};

template<class T>
class List
{
	typedef ListNode<T> Node;
public:
	typedef __ListIterator<T, T&, T*> iterator;
	typedef __ListIterator<T, const T&, const T*> const_iterator;

	
	List()
		:_head(new Node)
	{
		_head->_next = _head;
		_head->_prev = _head;
	}

	iterator begin()
	{
		return _head->_next;
	}

	const_iterator end() const
	{
		return _head;
	}

	const_iterator begin() const
	{
		return const_iterator(_head->_next);
	}

	iterator end()
	{
		return iterator(_head);
	}

	void PushBack(const T& x)
	{
		Node* tail = _head->_prev;
		Node* newnode = new Node(x);

		tail->_next = newnode;
		newnode->_prev = tail;

		newnode->_next = _head;
		_head->_prev = newnode;
	}
private:
	Node* _head;
};

struct AA
{
	int _a1;
	int _a2;
};

void TestList1()
{
	List<int> l;
	l.PushBack(1);
	l.PushBack(2);
	l.PushBack(3);

	List<int>::iterator it = l.begin();
	while (it != l.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	for (auto e : l)
	{
		cout << e << " ";
	}
	cout << endl;

	List<AA> laa;
	AA aa1 = { 1, 2 };
	laa.PushBack(aa1);
	laa.PushBack({3, 4});
	List<AA>::iterator ita = laa.begin();
	while (ita != laa.end())
	{
		//cout << (*ita)._a1 << (*ita)._a2 << endl;
		cout << ita->_a1 << ita->_a2 << endl;

		++ita;
	}

	AA* pa = new AA;
	pa->_a1 = 10;
	cout << (*pa)._a1 << endl;

	int* pi = new int;
	*pi;
}

list和vector的对比

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值