C++ list usage
general
Defined in the header file < list >, std::list is a container that supports constant time to insert and remove elements from any location of the container. Fast random access is not supported. It is usually implemented as a two-way linked list. With STD:: forward_ Compared with list, this container provides two-way iteration, but it is slightly inefficient in space.
Adding, removing, and moving elements within or between list s does not outlaw iterators or references. Iterators are illegal only when the corresponding element is deleted.
Class template:
template< class T, class Allocator = std::allocator<T> > class list;
Template parameters:
T - type of element;
Allocator - Allocator used to get / free memory and construct / destruct elements in memory.
create list
constructor
construct new containers from various data sources, optionally using the user provided allocator alloc.
same as vector and deque constructors.
definition:
// 1. Default constructor list(); // 2. Construct an empty container with the given allocator alloc. explicit list( const Allocator& alloc ); // 3. Construct a container with count elements with value. list( size_type count, const T& value, const Allocator& alloc = Allocator()); // 4. Construct a container with T instances inserted by count by default. Do not copy. explicit list( size_type count, const Allocator& alloc = Allocator() ); // 5. Construct a container with the contents of the scope [first, last]. template< class InputIt > list( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); // 6. Copy constructor list( const vector& other ); // 7. Construct a container with other content and use alloc as the allocator. list( const vector& other, const Allocator& alloc ); // 8. Move constructor list( vector&& other ); // 9. Mobile constructor with allocator extension. list( vector&& other, const Allocator& alloc ); // 10. Construct has initializer_list init content container. list( std::initializer_list<T> init, const Allocator& alloc = Allocator() );
Usage:
// 1. Default constructor std::list<std::string> words1; // 3. Construct a container with count elements with value std::list<std::string> words3(5, "Mo"); //words2 is {"Mo", "Mo", "Mo", "Mo"} // 5. Construct a container with the contents of the range [first, last] std::list<std::string> words5(words3.begin(), words3.end()); // 6. Copy constructor std::list<std::string> words6(words5); // 8. Move constructor std::list<std::string> words8(std::move(words6)); // 10. C++ 11 initializer list syntax: std::list<std::string> words10 {"the", "frogurt", "is", "also", "cursed"};
opertor=
replace the contents of the container.
definition:
list& operator=( const list& other ); // Copy assignment operator. list& operator=( list&& other ); // Move assignment operator. list& operator=( std::initializer_list<T> ilist ); // With initializer_ List the replacement content of the person identified by IList.
Usage:
std::list<int> nums1 {3, 1, 4, 6, 5, 9}; std::list<int> nums2; std::list<int> nums3; // Copy assignment data from nums1 to nums2 nums2 = nums1; // Move the assignment data from nums1 to nums3, nums3 = std::move(nums1); // initializer_ Copy assignment of list copy data to nums3 nums3 = {1, 2, 3};
assign
replace the contents of the container.
definition:
void assign( size_type count, const T& value ); // 1. Replace the content with a copy of count value. template< class InputIt > // 2. Replace the content with a copy of the element in the range [first, last]. void assign( InputIt first, InputIt last ); void assign( std::initializer_list<T> ilist ); // 3. From initializer_list ilist element replacement content.
Usage:
// Replace the content with a copy of count value std::list<char> characters; characters.assign(5, 'a'); // Replace the content with a copy of the element in the range [first, last] std::list<char> vchar; vchar.assign(characters.begin(), characters.end()); // From initializer_ Element replacement of list IList characters.assign({'\n', 'C', '+', '+', '1', '1', '\n'});
element access
front
returns a reference to the first element of the container.
For container C, the expression c.front() is equivalent to * c.begin().
definition:
reference front(); const_reference front() const;
Usage:
std::list<char> letters {'o', 'm', 'g', 'w', 't', 'f'}; if (!letters.empty()) { std::cout << letters.front() << std::out; // Output o }
back
returns a reference to the last element in the container.
For non empty container C, the expression c.back() is equivalent to * std::prev(c.end()).
definition:
reference back(); const_reference back() const;
Usage:
std::list<char> letters {'o', 'm', 'g', 'w', 't', 'f'}; if (!letters.empty()) { std::cout << letters.back() << std::endl; // Output f }
iterator
begin\cbegin
returns the iterator pointing to the first element of the list. c in cbegin means const, that is, const is returned_ Iterator, it is not allowed to modify elements through iterators.
If vector is empty, iterator returned will be equal to end().
definition:
iterator begin(); const_iterator cbegin() const noexcept;
Usage:
std::list<int> vi = {1, 2, 3, 4, 5, 6}; std::cout << *(vi.begin()) << std::endl; // Output 1 *(vi.begin()) = 0; std::cout << *(vi.cbegin()) << std::endl; // Output 0
end\cend
Point to the iterator that follows the last element.
definition:
iterator end(); const_iterator cend() const noexcept;
Usage:
std::deque<char> vc; if (vc.begin() == vc.end()) { std::cout << "vector is empty." << std::endl; }
rbegin\crbegin
returns the inverse iterator pointing to the first element of the inverse list. It corresponds to the last element of a non reverse list. If the list is empty, the iterator returned is equal to rend().
definition:
reverse_iterator rbegin(); const_reverse_iterator crbegin() const noexcept;
Usage:
std::list<int> vi = {1, 2, 3, 4, 5, 6}; std::cout << *(vi.rbegin()) << std::endl; // Output 6 std::cout << *(vi.crbegin()) << std::endl; // Output 6
rend\crend
returns the inverse iterator pointing to the last element of the inverse list. It corresponds to the previous element of the first element of the non reverse list. This element behaves as a placeholder and attempts to access it result in undefined behavior.
definition:
reverse_iterator rend(); const_reverse_iterator crend() const noexcept;
Usage:
std::list<int> vi = {1, 2, 3, 4, 5, 6}; std::cout << *std::prev(vi.rend()) << std::endl; // Output 1 std::cout << *std::prev(vi.crend()) << std::endl; // Output 1
capacity
empty
check whether the container has no elements, that is, whether begin() == end().
definition:
bool empty() const;
Usage:
list<int> v; bool flag = v.empty(); // Output true
size
returns the number of elements contained. That is, std::distance(begin(), end()).
definition:
size_type size() const;
Usage:
std::list<int> nums {1, 3, 5, 7}; std::cout << nums.size() << std::endl; // Output 4
max_size
returns the maximum number of elements that can be held by the container limited by the system or library implementation, that is, std::distance(begin(), end()) for the largest container.
definition:
size_type max_size() const;
Usage:
std::list<int> vi; std::cout << vi.max_size() << std::endl; // Possible output 4611686018427387903 std::list<char> vc; std::cout << vc.max_size() << std::endl; // Possible output 18446744073709551615
modifier
clear
erase all elements from the container. size() returns zero after this call.
illegal any reference, pointer, or iterator that refers to the contained element. Any trailing iterator is also illegal.
definition:
void clear();
Usage:
std::list<int> container{1, 2, 3}; container.clear(); std::cout << container.size() << std::endl; // Output 0
insert
insert the element into the specified position in the container.
definition:
// 1. Insert value before pos iterator insert( iterator pos, const T& value ); // 2. Insert value before pos iterator insert( const_iterator pos, T&& value ); // 3. Insert count copies of value before pos void insert( iterator pos, size_type count, const T& value ); // 4. Insert elements from the range [first, last] before pos template< class InputIt > void insert( iterator pos, InputIt first, InputIt last); // 5. Insert from initializer before pos_ Elements of list IList iterator insert( const_iterator pos, std::initializer_list<T> ilist );
Usage:
std::list<int> vec(3,100); // 1. 2. Insert value before pos auto it = vec.begin(); it = vec.insert(it, 200); // 200 100 100 100 // 3. Insert multiple value s vec.insert(it,2,300); // 300 300 200 100 100 100 // 4. Insert elements from the range [first, last] before pos std::list<int> vec2(2,400); vec.insert(vec.begin() + 2, vec2.begin(), vec2.end()); // 300 300 400 400 200 100 100 100 // 5. Insert from initializer before pos_ Elements of list IList int arr[] = { 501,502,503 }; vec.insert(vec.begin(), arr, arr+3); // 501 502 503 300 300 400 400 200 100 100 100
emplace
insert the element into the container directly before pos.
definition:
template< class... Args > iterator emplace( const_iterator pos, Args&&... args );
Usage:
std::list<int> v {1, 2, 3}; v.emplace(v.begin() + 1, 4); // v : 1, 4, 2, 3
erase
erase the specified element from the container.
definition:
// 1. Remove the element at pos. iterator erase( iterator pos ); // 2. Remove elements from the range [first; last]. iterator erase( iterator first, iterator last );
Usage:
std::deque<int> c {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; c.erase(c.begin()); // 1 2 3 4 5 6 7 8 9 c.erase(c.begin()+2, c.begin()+5); // 1 2 6 7 8 9 (front opening and rear closing, 6 has not been deleted)
push_back
attach the given element value to the end of the container
definition:
// 1. Initializes a copy of the new element as value. void push_back( const T& value ); // 2. Move value into new element. void push_back( T&& value );
Usage:
std::list<std::string> letters; letters.push_back("abc"); // letters : "abc" std::string s = "def"; letters.push_back(std::move(s)); // Letters: "ABC" "def", s is empty
emplace_back
add a new element to the end of the container
definition:
// C++ 11 template< class... Args > void emplace_back( Args&&... args ); // C++ 17 template< class... Args > reference emplace_back( Args&&... args );
Usage:
// Use empty for the following code_ The President type object is attached to std::deque after the back. // It demonstrates empty_ How back forwards parameters to the constructor of the President, // And show how to use empty_ Back avoid using push_ Additional copy or move operations during back. #include <deque> #include <string> #include <iostream> struct President { std::string name; std::string country; int year; President(std::string p_name, std::string p_country, int p_year) : name(std::move(p_name)), country(std::move(p_country)), year(p_year) { std::cout << "I am being constructed.\n"; } President(President&& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "I am being moved.\n"; } President& operator=(const President& other) = default; }; int main() { std::list<President> elections; std::cout << "emplace_back:\n"; elections.emplace_back("Nelson Mandela", "South Africa", 1994); std::list<President> reElections; std::cout << "\npush_back:\n"; reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); std::cout << "\nContents:\n"; for (President const& president: elections) { std::cout << president.name << " was elected president of " << president.country << " in " << president.year << ".\n"; } for (President const& president: reElections) { std::cout << president.name << " was re-elected president of " << president.country << " in " << president.year << ".\n"; } } // output emplace_back: I am being constructed. push_back: I am being constructed. I am being moved. Contents: Nelson Mandela was elected president of South Africa in 1994. Franklin Delano Roosevelt was re-elected president of the USA in 1936.
pop_back
remove the last element of the container.
definition:
void pop_back();
Usage:
std::list<int> numbers {1, 2, 3}; numbers.pop_back(); // {1, 2}
push_front
attach the given element value to the beginning of the container. After iterator, all iterators are illegal
definition:
void push_front( const T& value ); void push_front( T&& value );
Usage:
std::list<int> numbers {1, 2}; numbers.push_front(0); // {0, 1, 2}
emplace_front
insert a new element to the beginning of the container.
definition:
// C++ 11 template< class... Args > void emplace_front( Args&&... args ); // C++ 17 template< class... Args > reference emplace_front( Args&&... args );
Usage: refer to empty_ Use of back.
pop_front
remove the container header element. Iterators and references to erased elements are illegal.
definition:
void pop_front();
Usage:
std::list<int> c = {1, 2, 3}; c.pop_front(); // c : 2, 3
resize
resize the container to accommodate count elements. If the current size is greater than count, reduce the container to its first count element. If the current size is less than count, 1) additional default inserted elements are attached, and 2) additional copies of value are attached.
definition:
void resize( size_type count ); void resize( size_type count, const value_type& value );
Usage:
std::list<int> c = {1, 2, 3}; c.resize(5); // c : 1, 2, 3, 0, 0 c.resize(2); // c : 1, 2
swap
exchange of content with other. No move, copy, or swap operations are invoked on individual elements.
definition:
void swap( vector& other );
Usage:
std::list<int> a1{1, 2, 3}, a2{4, 5}; a1.swap(a2);
operation
merge
merge two sorted linked lists into one. The linked list should be sorted in ascending order.
definition:
void merge( list&& other ); template <class Compare> void merge( list&& other, Compare comp );
Usage:
std::list<int> list1 = { 5,9,0,1,3 }; std::list<int> list2 = { 8,7,2,6,4 }; list1.sort(); list2.sort(); list1.merge(list2); // list1 : 0 1 2 3 4 5 6 7 8 9 listt2.size(); // 0 list2 is empty
splice
transfer elements from one list to another. Do not copy or move elements, but only re point to the internal pointer of the linked list node.
definition:
// 1. Transfer all elements from other to * this. The element is inserted before the element pointed to by the pos. After the operation, the container other becomes empty. If other and * this refer to the same object, the behavior is undefined. void splice( const_iterator pos, list&& other ); // 2. Transfer the element it points to from other to * this. The element is inserted before the element pointed to by the pos. void splice( const_iterator pos, list&& other, const_iterator it ); // 3. Transfer the element in the range [first, last] from other to * this. The element is inserted before the element pointed to by pos. if POS is an iterator in the range [first, last], the behavior is undefined. void splice( const_iterator pos, list&& other, const_iterator first, const_iterator last );
Usage:
std::list<int> list1 = { 1, 2, 3, 4, 5 }; std::list<int> list2 = { 10, 20, 30, 40, 50 }; auto it = list1.begin(); std::advance(it, 2); // The iterator moves back 2 bits list1.splice(it, list2); std::cout << "list1: " << list1 << "\n"; // 1 2 10 20 30 40 50 3 4 5 std::cout << "list2: " << list2 << "\n"; // list2 is empty list2.splice(list2.begin(), list1, it, list1.end()); std::cout << "list1: " << list1 << "\n"; // 1 2 10 20 30 40 50 std::cout << "list2: " << list2 << "\n"; // 3 4 5
remove,remove_if
remove all elements that meet specific criteria. The first version removes all elements equal to value, and the second version removes all elements for which the predicate p returns true.
definition:
void remove( const T& value ); // (before C++20) size_type remove( const T& value ); // (from C++20) template< class UnaryPredicate > // (before C++20) void remove_if( UnaryPredicate p ); template< class UnaryPredicate > // (from C++20) size_type remove_if( UnaryPredicate p );
Usage:
std::list<int> l = { 1,100,2,3,10,1,11,-1,12 }; // Remove two elements equal to 1 l.remove(1); // 100, 2, 3, 10, 11, -1, 12 // Remove all elements greater than 10 l.remove_if([](int n){ return n > 10; }); // 2, 3, 10, -1
reverse
reverse the order of elements in the container. Do not illegal any references or iterators.
definition:
void reverse();
Usage:
std::list<int> list = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; list.reverse(); // 9 8 7 6 5 4 3 2 1 0
unique
* * remove all successive duplicate elements from the container. Only the first element in the group of equal elements is left** The first version compares elements with operator = = and the second version compares elements with binary predicate p
definition:
void unique(); // (before C++20) size_type unique(); // (after C++20) template< class BinaryPredicate > void unique( BinaryPredicate p ); // (before C++20) template< class BinaryPredicate > size_type unique( BinaryPredicate p ); // (from C++20)
Usage:
std::list<int> x = {1, 2, 2, 3, 3, 2, 1, 1, 2}; x.unique(); for (auto val : x) { std::cout << ' ' << val; // 1 2 3 2 1 2 }
sort
sort elements in ascending order. Maintain the order of equal elements. The first version uses operator < to compare elements, and the second version uses the given comparison function comp.
definition:
void sort(); template< class Compare > void sort( Compare comp );
Usage:
std::list<int> list = { 8,7,5,9,0,1,3,2,6,4 }; list.sort(); std::cout << "ascending: " << list << "\n"; // 0 1 2 3 4 5 6 7 8 9 list.sort(std::greater<int>()); std::cout << "descending: " << list << "\n"; // 9 8 7 6 5 4 3 2 1 0
non member function
operator==
check whether the contents of lhs and rhs are equal, that is, whether they have the same number of elements and each element in lhs is equal to the same location element of rhs.
definition:
template< class T, class Alloc > bool operator==( const std::deque<T,Alloc>& lhs, const std::deque<T,Alloc>& rhs );
Usage:
std::list<int> alice{1, 2, 3}; std::list<int> bob{7, 8, 9, 10}; std::list<int> eve{1, 2, 3}; // Compare unequal containers std::cout << "alice == bob returns " << (alice == bob) << std::endl; //Output false // Compare equal containers std::cout << "alice == eve returns " << (alice == eve) << std::endl; //Output true
std::swap
specialize std::swap algorithm for std::deque. Exchange the contents of lhs and RHS. Call lhs swap(rhs) .
definition:
template< class T, class Alloc > void swap( std::list<T,Alloc>& lhs, std::list<T,Alloc>& rhs );
Usage:
std::list<int> alice{1, 2, 3}; std::list<int> bob{7, 8, 9, 10}; //Exchange container std::swap(alice,bob); //After exchange: Alice: 7 8 9 10 bob : 1 2 3
erase(std::deque)
erase all elements with comparison equal to value from the container. (C++ 20)
definition:
template< class T, class Alloc, class U > constexpr typename std::list<T,Alloc>::size_type erase(std::list<T,Alloc>& c, const U& value);
Usage:
std::list<char> cnt {'1', '2', '3', '5', '6'}; auto erased = std::erase(cnt, '3');
erase_if(std::deque)
erase all elements satisfying pred from the container. (C++ 20)
definition:
template< class T, class Alloc, class U > constexpr typename std::list<T,Alloc>::size_type erase_if(std::list<T,Alloc>& c, Pred pred);
Usage:
std::list<char> cnt {'1', '2', '3', '5', '6'}; std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; } );