Write a program to insert elements in c++ STL list with the output.
The Standard Template Library is a software library for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called algorithms, containers, functions, and iterators.
How to insert elements in C++ STL List?
Copy the below c++ program and execute it to see the real time output. We have executed the below program and added at the end of page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include<iostream> #include<list> using namespace std; void display(list<int> my_list){ for (auto it = my_list.begin(); it != my_list.end(); ++it) cout << *it << " "; } int main() { int arr[] = {10, 41, 54, 20, 23, 69, 84, 75}; int n = sizeof(arr)/sizeof(arr[0]); list<int> my_list; for(int i = 0; i<n; i++){ my_list.push_back(arr[i]); } cout << "List before insertion: "; display(my_list); //insert 100 at front my_list.push_front(100); //insert 500 at back my_list.push_back(500); //insert 1000 at index 5 list<int>::iterator it = my_list.begin(); advance(it, 5); my_list.insert(it, 1000); cout << "\nList after insertion: "; display(my_list); } |
Program Output:
1 2 |
List before insertion: 10 41 54 20 23 69 84 75 List after insertion: 100 10 41 54 20 1000 23 69 84 75 500 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.