The list::insert() is used to insert the elements at any position of list. This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1.
Syntax:
insert(pos_iter, ele_num, ele)
Parameters: This function takes in three parameters:
- pos_iter: Position in the container where the new elements are inserted.
- ele_num: Number of elements to insert. Each element is initialized to a copy of val.
- ele: Value to be copied (or moved) to the inserted elements.
Return Value: This function returns an iterator that points to the first of the newly inserted elements.
// C++ code to demonstrate the working of // insert() function #include <iostream> #include <list> // for list operations using namespace std; int main() { // declaring list list<int> list1; // using assign() to insert multiple numbers // creates 3 occurrences of "2" list1.assign(3, 2); // initializing list iterator to beginning list<int>::iterator it = list1.begin(); // iterator to point to 3rd position advance(it, 2); // using insert to insert 1 element at the 3rd position // inserts 5 at 3rd position list1.insert(it, 5); // Printing the new list cout << "The list after inserting" << " 1 element using insert() is : "; for (list<int>::iterator i = list1.begin(); i != list1.end(); i++) cout << *i << " "; cout << endl; // using insert to insert // 2 element at the 4th position // inserts 2 occurrences // of 7 at 4th position list1.insert(it, 2, 7); // Printing the new list cout << "The list after inserting" << " multiple elements " << "using insert() is : "; for (list<int>::iterator i = list1.begin(); i != list1.end(); i++) cout << *i << " "; cout << endl; } |
The list after inserting 1 element using insert() is : 2 2 5 2 The list after inserting multiple elements using insert() is : 2 2 5 7 7 2
Recommended Posts:
- How to insert elements in C++ STL List ?
- map insert() in C++ STL
- multimap insert() in C++ STL
- unordered_map insert in C++ STL
- set insert() function in C++ STL
- emplace vs insert in C++ STL
- unordered_multimap insert() in C++ STL
- std::string::insert() in C++
- vector insert() function in C++ STL
- unordered_multiset insert() function in C++ STL
- unordered_set insert() function in C++ STL
- deque insert() function in C++ STL
- 2-3 Trees | (Search and Insert)
- Insert string at specified position in PHP
- multiset insert() function in C++ STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



