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的對比

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章