C++ 标准模板库STL 双向链表 list 使用方法与应用介绍(一)
STL中的list就是一双向链表,可高效地进行插入删除元素。List 是C++标准程式库中的一个类,可以简单视之为双向连结串行,以线性列的方式管理物件集合。list 的特色是在集合的任何位置增加或删除元素都很快,但是不支持随机存取。list 是C++标准程式库提供的众多容器(container)之一,除此之外还有vector、set、map、…等等。list 以模板方式实现(即泛型),可以处理任意型别的变量,包括使用者自定义的资料型态,例如:它可以是一个放置整数(int)型态的 list、也可以是放置字串(char 或 string)型态的 list、或者放置使用者自定类别(user-defined class)的 list。
list 被定义在 <list> 标头档中。一如其他STL元件,list属于std名称空间。
list 内部以数据结构的双向连结串行实做,内部元素并非放置于连续大块内存中,而是散落于内存各处,互相以link串接起来,每个元素都只知道其前一个元素以及下一个元素的位置。故要走访整个list,必须从第一个元素开始逐个往下寻访,不支持随机存取(Random Access)。 list 的强项是高效的插入以及删除,于list插入或删除时只需要改动元素的link字段,不需要搬动元素,代价相对便宜。
list 在经常需要于集合内部任意位置(即除了头尾以外的其他位置) 频繁增删元素的工作上表现优秀。若仅需要于集合尾端增删元素,那应该优先考虑vector容器,若仅于头尾二端增删元素,那应该优先考虑deque容器。
成员函数概观
- Iterators:
list.begin()
回传指向第一个元素的 Iterator。list.end()
回传指向最末元素的下一个位置的 Iterator。list.rbegin()
回传指向最末个元素的反向 Iterator。list.rend()
回传指向第一个元素的前一个位置的反向 Iterator。
- Capacity/Size:
list.empty()
若list内部为空,则回传true值。list.size()
回传list内实际的元素个数。lsit.resize()
重新分派list的长度。
- Element Access
list.front()
存取第一个元素。list.back()
存取最末个元素。
- Modify methods
list.push_front()
增加一个新的元素在 list 的前端。list.pop_front()
删除 list 的第一个元素。list.push_back()
增加一个新的元素在 list 的尾端。list.pop_back()
删除 list 的最末个元素。
构造:
list<int> c0; //空链表
list<int> c1(3); //建一个含三个默认值是0的元素的链表
list<int> c2(5,2); //建一个含五个元素的链表,值都是2
list<int> c4(c2); //建一个c2的copy链表
list<int> c5(c1.begin(),c1.end()); ////c5含c1一个区域的元素[First, Last)。
方法:
assign() //分配值,有两个重载:
c1.assign(c2.begin(), c2.end())
c1.assign(7,4) //c1中现在为7个4,c1(4,4,4,4,4,4,4)。
back() //返回最后一元素的引用:
begin() //返回第一个元素的指针(iterator)
clear() //删除所有元素
empty() //判断是否链表为空
end() //返回最后一个元素的下一位置的指针(list为空时end()=begin())
erase() //删除一个元素或一个区域的元素(两个重载)
front() //返回第一个元素的引用:
insert() //在指定位置插入一个或多个元素(三个重载):
merge() //合并两个链表并使之默认升序(也可改):
pop_back() //删除链表尾的一个元素
pop_front() //删除链表头的一元素
push_back() //增加一元素到链表尾
push_front() //增加一元素到链表头
remove //()删除链表中匹配值的元素(匹配元素全部删除)
remove_if() //删除条件满足的元素(会遍历一遍链表)
reverse() //反转链表:
size() //返回链表中元素个数
sort() //对链表排序,默认升序(可自定义)
swap() //交换两个链表(两个重载)
unique() //删除相邻重复元素(断言已经排序,因为它不会删除不相邻的相同元素)
Members
Member | Where defined | Description |
---|---|---|
value_type | Container | The type of object, T, stored in the list. |
pointer | Container | Pointer to T. |
reference | Container | Reference to T |
const_reference | Container | Const reference to T |
size_type | Container | An unsigned integral type. |
difference_type | Container | A signed integral type. |
iterator | Container | Iterator used to iterate through a list. |
const_iterator | Container | Const iterator used to iterate through a list. |
reverse_iterator | Reversible Container | Iterator used to iterate backwards through a list. |
const_reverse_iterator | Reversible Container | Const iterator used to iterate backwards through a list. |
iterator begin() | Container | Returns an iterator pointing to the beginning of the list. |
iterator end() | Container | Returns an iterator pointing to the end of the list. |
const_iterator begin() const | Container | Returns a const_iterator pointing to the beginning of the list. |
const_iterator end() const | Container | Returns a const_iterator pointing to the end of the list. |
reverse_iterator rbegin() | Reversible Container | Returns a reverse_iterator pointing to the beginning of the reversed list. |
reverse_iterator rend() | Reversible Container | Returns a reverse_iterator pointing to the end of the reversed list. |
const_reverse_iterator rbegin() const | Reversible Container | Returns a const_reverse_iterator pointing to the beginning of the reversed list. |
const_reverse_iterator rend() const | Reversible Container | Returns a const_reverse_iterator pointing to the end of the reversed list. |
size_type size() const | Container | Returns the size of the list. Note: you should not assume that this function is constant time. It is permitted to be O(N), where N is the number of elements in the list. If you wish to test whether a list is empty, you should write L.empty() rather than L.size() == 0. |
size_type max_size() const | Container | Returns the largest possible size of the list. |
bool empty() const | Container | true if the list's size is 0. |
list() | Container | Creates an empty list. |
list(size_type n) | Sequence | Creates a list with n elements, each of which is a copy of T(). |
list(size_type n, const T& t) | Sequence | Creates a list with n copies of t. |
list(const list&) | Container | The copy constructor. |
template <class InputIterator> list(InputIterator f, InputIterator l) [2] |
Sequence | Creates a list with a copy of a range. |
~list() | Container | The destructor. |
list& operator=(const list&) | Container | The assignment operator |
reference front() | Front Insertion Sequence | Returns the first element. |
const_reference front() const | Front Insertion Sequence | Returns the first element. |
reference back() | Sequence | Returns the last element. |
const_reference back() const | Back Insertion Sequence | Returns the last element. |
void push_front(const T&) | Front Insertion Sequence | Inserts a new element at the beginning. |
void push_back(const T&) | Back Insertion Sequence | Inserts a new element at the end. |
void pop_front() | Front Insertion Sequence | Removes the first element. |
void pop_back() | Back Insertion Sequence | Removes the last element. |
void swap(list&) | Container | Swaps the contents of two lists. |
iterator insert(iterator pos, const T& x) | Sequence | Inserts x before pos. |
template <class InputIterator> void insert(iterator pos, InputIterator f, InputIterator l) [2] |
Sequence | Inserts the range [f, l) before pos. |
void insert(iterator pos, size_type n, const T& x) |
Sequence | Inserts n copies of x before pos. |
iterator erase(iterator pos) | Sequence | Erases the element at position pos. |
iterator erase(iterator first, iterator last) | Sequence | Erases the range [first, last) |
void clear() | Sequence | Erases all of the elements. |
void resize(n, t = T()) | Sequence | Inserts or erases elements at the end such that the size becomes n. |
void splice(iterator pos, list& L) | list | See below. |
void splice(iterator pos, list& L, iterator i) |
list | See below. |
void splice(iterator pos, list& L, iterator f, iterator l) |
list | See below. |
void remove(const T& value) | list | See below. |
void unique() | list | See below. |
void merge(list& L) | list | See below. |
void sort() | list | See below. |
bool operator==(const list&, const list&) |
Forward Container | Tests two lists for equality. This is a global function, not a member function. |
bool operator<(const list&, const list&) |
Forward Container | Lexicographical comparison. This is a global function, not a member function. |
New members
These members are not defined in the Reversible Container, Front Insertion Sequence, and Back Insertion Sequencerequirements, but are specific to list.Function | Description |
---|---|
void splice(iterator position, list<T, Alloc>& x); |
position must be a valid iterator in *this, and x must be a list that is distinct from *this. (That is, it is required that &x != this.) All of the elements of x are inserted before position and removed from x. All iterators remain valid, including iterators that point to elements of x. [3] This function is constant time. |
void splice(iterator position, list<T, Alloc>& x, iterator i); |
position must be a valid iterator in *this, and i must be a dereferenceable iterator in x. Splice moves the element pointed to by i from x to *this, inserting it before position. All iterators remain valid, including iterators that point to elements of x. [3] If position == i or position == ++i, this function is a null operation. This function is constant time. |
void splice(iterator position, list<T, Alloc>& x, iterator f, iterator l); |
position must be a valid iterator in *this, and [first, last) must be a valid range in x. position may not be an iterator in the range [first, last). Splice moves the elements in [first, last) from x to *this, inserting them before position. All iterators remain valid, including iterators that point to elements of x. [3] This function is constant time. |
void remove(const T& val); | Removes all elements that compare equal to val. The relative order of elements that are not removed is unchanged, and iterators to elements that are not removed remain valid. This function is linear time: it performs exactly size() comparisons for equality. |
template<class Predicate> void remove_if(Predicate p); [4] |
Removes all elements *i such that p(*i) is true. The relative order of elements that are not removed is unchanged, and iterators to elements that are not removed remain valid. This function is linear time: it performs exactly size() applications of p. |
void unique(); | Removes all but the first element in every consecutive group of equal elements. The relative order of elements that are not removed is unchanged, and iterators to elements that are not removed remain valid. This function is linear time: it performs exactly size() - 1 comparisons for equality. |
template<class BinaryPredicate> void unique(BinaryPredicate p); [4] |
Removes all but the first element in every consecutive group of equivalent elements, where two elements *i and *j are considered equivalent if p(*i, *j) is true. The relative order of elements that are not removed is unchanged, and iterators to elements that are not removed remain valid. This function is linear time: it performs exactly size() - 1 comparisons for equality. |
void merge(list<T, Alloc>& x); | Both *this and x must be sorted according to operator<, and they must be distinct. (That is, it is required that &x != this.) This function removes all of x's elements and inserts them in order into *this. The merge is stable; that is, if an element from *this is equivalent to one from x, then the element from *this will precede the one from x. All iterators to elements in *this and x remain valid. This function is linear time: it performs at most size() + x.size() - 1 comparisons. |
template<class BinaryPredicate> void merge(list<T, Alloc>& x, BinaryPredicate Comp); [4] |
Comp must be a comparison function that induces a strict weak ordering (as defined in the LessThan Comparable requirements) on objects of type T, and both *this and x must be sorted according to that ordering. The lists x and *this must be distinct. (That is, it is required that &x != this.) This function removes all of x's elements and inserts them in order into *this. The merge is stable; that is, if an element from *this is equivalent to one from x, then the element from *this will precede the one from x. All iterators to elements in *this and x remain valid. This function is linear time: it performs at most size() + x.size() - 1 applications of Comp. |
void reverse(); | Reverses the order of elements in the list. All iterators remain valid and continue to point to the same elements. [5] This function is linear time. |
void sort(); | Sorts *this according to operator<. The sort is stable, that is, the relative order of equivalent elements is preserved. All iterators remain valid and continue to point to the same elements. [6] The number of comparisons is approximately N log N, where N is the list's size. |
template<class BinaryPredicate> void sort(BinaryPredicate comp); [4] |
Comp must be a comparison function that induces a strict weak ordering (as defined in the LessThan Comparable requirements on objects of type T. This function sorts the list *this according to Comp. The sort is stable, that is, the relative order of equivalent elements is preserved. All iterators remain valid and continue to point to the same elements. [6] The number of comparisons is approximately N log N, where N is the list's size. |
#include <iostream> #include <list> #include <algorithm> #include <iterator> using namespace std; void printLists (const list<int>& l1, const list<int>& l2) { cout << "list1: "; copy (l1.begin(), l1.end(), ostream_iterator<int>(cout," ")); cout << endl << "list2: "; copy (l2.begin(), l2.end(), ostream_iterator<int>(cout," ")); cout << endl << endl; } int main() { // create two empty lists list<int> list1, list2; // fill both lists with elements for (int i=0; i<6; ++i) { list1.push_back(i); list2.push_front(i); } printLists(list1, list2); // insert all elements of list1 before the first element with value 3 of list2 // - find() returns an iterator to the first element with value 3 list2.splice(find(list2.begin(),list2.end(), // destination position 3), list1); // source list printLists(list1, list2); // move first element to the end list2.splice(list2.end(), // destination position list2, // source list list2.begin()); // source position printLists(list1, list2); // sort second list, assign to list1 and remove duplicates list2.sort(); list1 = list2; list2.unique(); printLists(list1, list2); // merge both sorted lists into the first list list1.merge(list2); printLists(list1, list2); } /********************** 运行结果: list1: 0 1 2 3 4 5 list2: 5 4 3 2 1 0 list1: list2: 5 4 0 1 2 3 4 5 3 2 1 0 list1: list2: 4 0 1 2 3 4 5 3 2 1 0 5 list1: 0 0 1 1 2 2 3 3 4 4 5 5 list2: 0 1 2 3 4 5 list1: 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 list2: Process returned 0 (0x0) execution time : 0.959 s Press any key to continue. ***********************/
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步