Lists are sequence containers available in the C++ Standard Library. They allow non-contiguous memory allocation. List containers are implemented as doubly-linked lists. Compared to other sequence containers (eg: arrays, vectors etc.), lists have a better performance when it comes to inserting, moving or deleting elements. The list::insert()
is a method available in the STL which inserts a new element(s) before the element at the specified position.
Syntax:
list_name.insert(iterator_position, value); //single element list_name.insert(iterator_position, n, value); //insert n elements of 'value' list_name.insert(iterator_position, first_iterator, last_iterator) // copies of the elements in the range [first_iterator,last_iterator)
Parameters: The list::insert()
method accepts various parameters:
•Position in the container where the new elements are inserted (iterator)
•Element to be inserted to the list (value)
•Number of elements to insert (n)
•Iterators specifying a range of elements (first, last)
Return value: An iterator that points to the first newly inserted element.
Example of list::insert() method
#include <iostream> #include <list> #include <vector> using namespace std; void print_list(list<int> L) { for( list<int>::iterator it = L.begin(); it != L.end(); ++it) { cout<<*it<<" <--> "; } cout<<"NULL"<<endl; } int main() { list<int> new_list; for(int i = 1; i <= 5; i++) { new_list.push_back(i); } print_list(new_list); list<int>::iterator it = new_list.begin(); it++; it++; //it points to 3 new_list.insert(it, 7); //inserting one element print_list(new_list); //NOTE: it still points to 3 new_list.insert(it, 2, 8); //inserting various elements print_list(new_list); //NOTE: it still points to 3 list<int> list2; list2.push_back(10); list2.push_back(11); new_list.insert(it, list2.begin(), list2.end()); //inserting using iterator range //NOTE: it still points to 3 print_list(new_list); return 0; }
Output:
1 <--> 2 <--> 3 <--> 4 <--> 5 <--> NULL 1 <--> 2 <--> 7 <--> 3 <--> 4 <--> 5 <--> NULL 1 <--> 2 <--> 7 <--> 8 <--> 8 <--> 3 <--> 4 <--> 5 <--> NULL 1 <--> 2 <--> 7 <--> 8 <--> 8 <--> 10 <--> 11 <--> 3 <--> 4 <--> 5 <--> NULL