📅  最后修改于: 2023-12-03 15:20:20.974000             🧑  作者: Mango
std::list
is a container in the C++ Standard Template Library (STL) that provides constant time insertion and removal of elements in any position.
The insert()
method of std::list
is used to insert elements at any position in the list.
iterator insert( const_iterator pos, const T& value );
iterator insert( const_iterator pos, T&& value );
iterator insert( const_iterator pos, size_type count, const T& value );
template< class InputIt >
iterator insert( const_iterator pos, InputIt first, InputIt last );
iterator insert( const_iterator pos, initializer_list<T> ilist );
pos
: Position where the element(s) will be inserted.value
: Element to be inserted in the list.count
: Number of elements to be inserted.first
and last
: Iterators to the beginning and end of a range of elements.ilist
: Initializer list of elements to be inserted.The method returns an iterator to the inserted element.
std::list<int> myList = {1, 2, 3};
auto it = myList.begin();
it++; // point to second element (value 2)
myList.insert(it, 4); // insert 4 before the second element (value 2)
// resultant list: {1, 4, 2, 3}
std::list<int> myList = {1, 2, 3};
auto it = myList.begin();
it++; // point to second element (value 2)
myList.insert(it, 3, 4); // insert 3 copies of 4 before the second element (value 2)
// resultant list: {1, 4, 4, 4, 2, 3}
std::list<int> myList = {1, 2, 3};
std::vector<int> vec = {4, 5, 6};
auto it = myList.begin();
it++; // point to second element (value 2)
myList.insert(it, vec.begin(), vec.end()); // insert the elements from vec before the second element (value 2)
// resultant list: {1, 4, 5, 6, 2, 3}
std::list<int> myList = {1, 2, 3};
auto it = myList.begin();
it++; // point to second element (value 2)
myList.insert(it, {4, 5, 6}); // insert the elements from the initializer list before the second element (value 2)
// resultant list: {1, 4, 5, 6, 2, 3}
The insert()
method of std::list
is a very useful method for inserting elements at any position in the container. It provides flexibility and convenience to the programmer, allowing them to choose from various options and approaches to insert elements in their list.