目录
迭代器
功能:
iterator
reverse_iterator
const_iterator
const_reverse_iterator
性质:
单向:forward_list/unordered_map... ++
双向:list/map/set(二叉树结构)... ++/--
随机:vector/string/deque(连续的物理空间).. ++/--/+/-底层结构----决定使用哪些算法
内存是否连续只能决定随机,但不能判断单双向
sort(随机迭代器)
list(双向迭代器)
vector(随记迭代器)
find(input迭代器--只读--可传任意类型迭代器)
尾插 push_back/emplace_back
插入数据
list<int> lt;
auto it=lt.begin();
int k=3;
while(k--)
{++it;}
lt.insert(it,30);
删除
it=find(lt.begin(),lt.end(),x);
if(it!=lt.end())
{lt.erase(it);}
交换(swap)
两个链表交换,不走深拷贝,直接交换头指针
排序
less<int> ls;//升序
greater<int>gt;//降序
lt.sort(gt);
lt.sort(greater<int>());//匿名对象
链表合并(merge)
链表合并(前提:两个链表有序)取小尾插
被合并的链表合并之后为空
// 合并两个链表
list1.merge(list2);
List 1: 1 3 5 7
List 2: 2 4 6 8
Merged List: 1 2 3 4 5 6 7 8
List 2 after merge (should be empty):
删除(remove)
剪切(splice)
一个链表的节点转移到该链表某一位置
// 一个链表节点转移给另一个链表
std::list<int> mylist1, mylist2;
std::list<int>::iterator it;
// set some initial values:
for (int i = 1; i <= 4; ++i)
mylist1.push_back(i); // mylist1: 1 2 3 4
for (int i = 1; i <= 3; ++i)
mylist2.push_back(i * 10); // mylist2: 10 20 30
it = mylist1.begin();
++it; // points to 2
mylist1.splice(it, mylist2); // mylist1: 1 10 20 30 2 3 4
// mylist2 (empty)
// "it" still points to 2 (the 5th element
// 调整当前链表节点的顺序
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.push_back(5);
lt.push_back(6);
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
int x = 0;
cin >> x;
it = find(lt.begin(), lt.end(), x);
if (it != lt.end())
{
//lt.splice(lt.begin(), lt, it);
lt.splice(lt.begin(), lt, it, lt.end());
}
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
去重(unique)
sort
算法库的sort 快排(递归)debug版本下较差
list的sort 适合少量数据的排序
底层实现
template<class T>
struct list_node
{
public:
T _data;
list_node<T>* _next;
list_node<T>* _prev;
};
template<class T>
class list
{
typedef list_node<T> Node;
public:
list()
{
_head=new Node;
_head->next=_head;
_head->prev=_head;
_size = 0;
}
private:
Node* _head;
size_t _size;
};
push_back();
void push_back(const T& x)
{
Node* newnode = new Node(x);
Node* tail = _head->_prev;
tail->_next = newnode;
newnode->_prev = tail;
newnode->_next = _head;
_head->_prev = newnode;
}
迭代器
// const_iterator
template<class T>
struct list_iterator
{
typedef list_node<T> Node;
typedef list_iterator<T> Self;
Node* _node;
list_iterator(Node* node)
:_node(node)
{}
T& operator*()
{
return _node->_data;
}
Self& operator++()
{
_node = _node->_next;
return *this;
}
Self& operator--()
{
_node = _node->_prev;
return *this;
}
bool operator!=(const Self& s) const
{
return _node != s._node;
}
bool operator==(const Self& s) const
{
return _node == s._node;
}
};
list链表
template<class T>
class list
{
typedef list_node<T> Node;
public:
typedef list_iterator<T> iterator;
iterator begin()
{
/* iterator it(_head->_next);
return it;*/
//return iterator(_head->_next);
return _head->_next;//返回节点的指针,接收的是iterator,节点的指针隐式类型转换为iterator
}
iterator end()//最后一个位置的下一个数据
{
return _head;
}
list()
{
_head = new Node;
_head->_next = _head;
_head->_prev = _head;
_size = 0;
}
void push_back(const T& x)
{
/*Node* newnode = new Node(x);
Node* tail = _head->_prev;
tail->_next = newnode;
newnode->_prev = tail;
newnode->_next = _head;
_head->_prev = newnode;
++_size;*/
insert(end(), x);
}
void push_front(const T& x)
{
insert(begin(), x);
}
void insert(iterator pos, const T& x)
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* newnode = new Node(x);
// prev newnode cur
newnode->_next = cur;
cur->_prev = newnode;
newnode->_prev = prev;
prev->_next = newnode;
++_size;
}
void pop_back()
{
erase(--end());
}
void pop_front()
{
erase(begin());
}
void erase(iterator pos)
{
assert(pos != end());
Node* prev = pos._node->_prev;
Node* next = pos._node->_next;
prev->_next = next;
next->_prev = prev;
delete pos._node;
--_size;
}
size_t size() const
{
return _size;
}
bool empty() const
{
return _size == 0;
}
private:
Node* _head;
size_t _size;
};
insert
void insert(iterator pos, const T& x)
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* newnode = new Node(x);
// prev newnode cur
newnode->_next = cur;
cur->_prev = newnode;
newnode->_prev = prev;
prev->_next = newnode;
++_size;
}
erase
void erase(iterator pos)
{
assert(pos != end());
Node* prev = pos._node->_prev;
Node* next = pos._node->_next;
prev->_next = next;
next->_prev = prev;
delete pos._node;
--_size;
}
pop_back/pop_front
void pop_back()
{
erase(--end());
}
void pop_front()
{
erase(begin());
}
ita
是一个迭代器,ita.operator->()
返回一个指向当前节点的指针。由于ita
是list_iterator
类型的对象,它本身并不直接包含_a1
和_a2
成员。相反,它指向一个list_node<AA>
对象,该对象包含_data
,而_data
是AA
类型的对象。解释
解引用操作:
*ita
会返回一个AA
对象(即当前节点的数据),然后你可以使用(*ita)._a1
和(*ita)._a2
访问其成员。- 这种方式是完全合法的,但在语法上稍显冗长。
箭头操作:
ita->
实际上是等价于(*ita).operator->()
,它返回指向AA
对象的指针,因此你可以直接访问_a1
和_a2
。
list<AA> lta;
lta.push_back(AA());
lta.push_back(AA());
lta.push_back(AA());
lta.push_back(AA());
list<AA>::iterator ita = lta.begin();
while (ita != lta.end())
{
//cout << (*ita)._a1 << ":" << (*ita)._a2 << endl;
// 特殊处理,本来应该是两个->才合理,为了可读性,省略了一个->
cout << ita->_a1 << ":" << ita->_a2 << endl;
cout << ita.operator->()->_a1 << ":" << ita.operator->()->_a2 << endl;
++ita;
}
cout << endl;
T* operator->()
{
return &_node->_data;
}
cout << *ita;
如果你想直接打印 *ita,需要确保 AA 类型重载了 operator<<。否则,编译器将不知道如何打印 AA 的对象。
#include <iostream>
struct AA {
int _a1 = 1;
int _a2 = 1;
// 重载 operator<<
friend std::ostream& operator<<(std::ostream& os, const AA& obj) {
os << obj._a1 << ":" << obj._a2;
return os;
}
};
const_iterator和iterator
operator*和operator-> 都不能修改
template<class Container>
void print_container(const Container& con)
{
// const iterator -> 迭代器本身不能修改
// const_iterator -> 指向内容不能修改
typename Container::const_iterator it = con.begin();
//auto it = con.begin();
while (it != con.end())
{
//*it += 10;
cout << *it << " ";
++it;
}
cout << endl;
for (auto e : con)
{
cout << e << " ";
}
cout << endl;
}
按需实例化 ------- 没有实例化对象,不会检查出来错误
改进:一个类模板实现两个类
template<class T, class Ref, class Ptr>
struct list_iterator
{
typedef list_node<T> Node;
typedef list_iterator<T, Ref, Ptr> Self;
Node* _node;
list_iterator(Node* node)
:_node(node)
{}
Ref operator*()
{
return _node->_data;
}
Ptr operator->()
{
return &_node->_data;
}
Self& operator++()
{
_node = _node->_next;
return *this;
}
Self& operator--()
{
_node = _node->_prev;
return *this;
}
Self operator++(int)
{
Self tmp(*this);
_node = _node->_next;
return tmp;
}
Self& operator--(int)
{
Self tmp(*this);
_node = _node->_prev;
return tmp;
}
bool operator!=(const Self& s) const
{
return _node != s._node;
}
bool operator==(const Self& s) const
{
return _node == s._node;
}
};
迭代器失效-----insert不失效,erase不失效
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
// insert以后迭代器不失效
list<int>::iterator it = lt.begin();
lt.insert(it, 10);
*it += 100;
print_container(lt);
// erase以后迭代器失效
// 删除所有的偶数
it = lt.begin();
while (it != lt.end())
{
if (*it % 2 == 0)
{
it = lt.erase(it);
}
else
{
++it;
}
}
print_container(lt);
erase需要更新迭代器
iterator erase(iterator pos)
{
assert(pos != end());
Node* prev = pos._node->_prev;
Node* next = pos._node->_next;
prev->_next = next;
next->_prev = prev;
delete pos._node;
--_size;
return next;
}
析构
~list()
{
clear();
delete _head;
_head = nullptr;
}
void clear()
{
auto it = begin();
while (it != end())
{
it = erase(it);
}
}
拷贝构造
void empty_init()
{
_head = new Node;
_head->_next = _head;
_head->_prev = _head;
_size = 0;
}
list()
{
empty_init();
}
list(initializer_list<T> il)
{
empty_init();
for (auto& e : il)
{
push_back(e);
}
}
赋值重载
// lt1 = lt3
list<T>& operator=(list<T> lt)
{
swap(lt);
return *this;
}
void swap(list<T>& lt)
{
std::swap(_head, lt._head);
std::swap(_size, lt._size);
}
std::swap
: 这个函数会安全地交换两个变量的值,适用于指针和基本数据类型- 内存管理: 如果你的
list
类使用动态内存分配(比如链表节点),确保在交换后不会出现内存泄漏或悬挂指针
关于swap函数:
错误写法:
void swap(list<T>& l)
{
_pHead = l._pHead;
_size = l._size;
}
swap
函数的目的是交换两个对象的内容,而不是简单地将一个对象的内容赋值给另一个对象
_pHead
和_size
的值会被覆盖,而不是交换。这意味着原本的链表会丢失其数据,导致内存泄漏或未定义行为
std::initializer_list
单独支持一个构造函数
list(initializer_list<T> il)
{
empty_init();
for (auto& e : il)
{
push_back(e);
}
}
void func(const list<int>& lt)
{
print_container(lt);
}
void test_list4()
{
// 直接构造
list<int> lt0({ 1,2,3,4,5,6 });
// 隐式类型转换
list<int> lt1 = { 1,2,3,4,5,6,7,8 };
const list<int>& lt3 = { 1,2,3,4,5,6,7,8 };
func(lt0);
func({ 1,2,3,4,5,6 });
print_container(lt1);
//auto il = { 10, 20, 30 };
/* initializer_list<int> il = { 10, 20, 30 };
cout << typeid(il).name() << endl;
cout << sizeof(il) << endl;*/
}
代码实现
namespace bite
{
// List的节点类
template<class T>
struct ListNode
{
ListNode(const T& val = T()): _pPre(nullptr), _pNext(nullptr), _val(val)
{}
ListNode<T>* _pPre;
ListNode<T>* _pNext;
T _val;
};
//List的迭代器类
template<class T, class Ref, class Ptr>
class ListIterator
{
typedef ListNode<T>* PNode;
typedef ListIterator<T, Ref, Ptr> Self;
public:
ListIterator(PNode pNode = nullptr):_pNode(pNode)
{}
ListIterator(const Self& l): _pNode(l._pNode)
{}
T& operator*()
{
return _pNode->_val;
}
T* operator->()
{
return &*this;
}
Self& operator++()
{
_pNode = _pNode->_pNext;
return *this;
}
Self operator++(int)
{
Self temp(*this);
_pNode = _pNode->_pNext;
return temp;
}
Self& operator--()
{
_pNode = _pNode->_pPre;
return *this;
}
Self& operator--(int)
{
Self temp(*this);
_pNode = _pNode->_pPre;
return temp;
}
bool operator!=(const Self& l)
{
return _pNode != l._pNode;
}
bool operator==(const Self& l)
{
return !(*this!=l);
}
private:
PNode _pNode;
};
//list类
template<class T>
class list
{
typedef ListNode<T> Node;
typedef Node* PNode;
public:
typedef ListIterator<T, T&, T*> iterator;
typedef ListIterator<T, const T&, const T&> const_iterator;
public:
///
// List的构造
list()
{
CreateHead();
}
list(int n, const T& value = T())
{
CreateHead();
for (int i = 0; i < n; ++i)
push_back(value);
}
template <class Iterator>
list(Iterator first, Iterator last)
{
CreateHead();
while (first != last)
{
push_back(*first);
++first;
}
}
list(const list<T>& l)
{
CreateHead();
// 用l中的元素构造临时的temp,然后与当前对象交换
list<T> temp(l.cbegin(), l.cend());
this->swap(temp);
}
list<T>& operator=(const list<T> l)
{
this->swap(l);
return *this;
}
~list()
{
clear();
delete _pHead;
_pHead = nullptr;
}
///
// List Iterator
iterator begin()
{
return iterator(_pHead->_pNext);
}
iterator end()
{
return iterator(_pHead);
}
const_iterator begin()const
{
return const_iterator(_pHead->_pNext);
}
const_iterator end()const
{
return const_iterator(_pHead);
}
///
// List Capacity
size_t size()const
{
size_t size = 0;
ListNode *p = _pHead->_pNext;
while(p != _pHead)
{
size++;
p = p->_pNext;
}
return size;
}
bool empty()const
{
return size() == 0;
}
// List Access
T& front()
{
assert(!empty());
return _pHead->_pNext->_val;
}
const T& front()const
{
assert(!empty());
return _pHead->_pNext->_val;
}
T& back()
{
assert(!empty());
return _pHead->_pPre->_val;
}
const T& back()const
{
assert(!empty());
return _pHead->_pPre->_val;
}
// List Modify
void push_back(const T& val)
{
insert(end(), val);
}
void pop_back()
{
erase(--end());
}
void push_front(const T& val)
{
insert(begin(), val);
}
void pop_front()
{
erase(begin());
}
// 在pos位置前插入值为val的节点
iterator insert(iterator pos, const T& val)
{
PNode pNewNode = new Node(val);
PNode pCur = pos._pNode;
// 先将新节点插入
pNewNode->_pPre = pCur->_pPre;
pNewNode->_pNext = pCur;
pNewNode->_pPre->_pNext = pNewNode;
pCur->_pPre = pNewNode;
return iterator(pNewNode);
}
// 删除pos位置的节点,返回该节点的下一个位置
iterator erase(iterator pos)
{
// 找到待删除的节点
PNode pDel = pos._pNode;
PNode pRet = pDel->_pNext;
// 将该节点从链表中拆下来并删除
pDel->_pPre->_pNext = pDel->_pNext;
pDel->_pNext->_pPre = pDel->_pPre;
delete pDel;
return iterator(pRet);
}
void clear()
{
iterator p = begin();
while(p != end())
{
p = erase(p);
}
_pHead->_pPrev = _pHead;
_pHead->_pNext = _pHead;
}
void swap(List<T>& l)
{
pNode tmp = _pHead;
_pHead = l._pHead;
l._pHead = tmp;
}
private:
void CreateHead()
{
_pHead = new Node;
_pHead->_pPre = _pHead;
_pHead->_pNext = _pHead;
}
PNode _pHead;
};
}