Nested list in C++ STL
list in STL is used to represent a linked list in C++. How to create a nested list. We are given n lists, we need to create a list of n lists.
Examples:
Input : Number of lists: 2
1st list: {1 2}
2nd list: {3 4 5 6
Output :
[
[ 1 2 ]
[ 3 4 5 6 ]
]
Input : Number of lists: 3
1st list : {0 1}
2nd list : {1 2 3}
3rd list : {2 3 4 5}
Output :
[
[ 0 1 ]
[ 1 2 3 ]
[ 2 3 4 5 ]
]
// c++ program for nested list #include <iostream> #include <iterator> #include <list> using namespace std; void printNestedList(list<list<int> > nested_list) { cout << "[\n"; // nested_list`s iterator(same type as nested_list) // to iterate the nested_list list<list<int> >::iterator nested_list_itr; // Print the nested_list for (nested_list_itr = nested_list.begin(); nested_list_itr != nested_list.end(); ++nested_list_itr) { cout << " ["; // normal_list`s iterator(same type as temp_list) // to iterate the normal_list list<int>::iterator single_list_itr; // pointer of each list one by one in nested list // as loop goes on list<int>& single_list_pointer = *nested_list_itr; for (single_list_itr = single_list_pointer.begin(); single_list_itr != single_list_pointer.end(); single_list_itr++) { cout << " " << *single_list_itr << " "; } cout << "]\n"; } cout << "]"; } // Driver code int main() { // instead integer type can have any data type list<list<int> > nested_list; list<int> single_list; int n, m, num; // number of lists in nested list n = 3; for (int i = 0; i < n; i++) { // number of elements in list m = i + 2; for (int j = 0; j < m; j++) { num = i + j; single_list.push_back(num); } nested_list.push_back(single_list); // delete all elements from single_list single_list.erase(single_list.begin(), single_list.end()); } printNestedList(nested_list); return 0; } |
chevron_right
filter_none
Output:
[ [ 0 1 ] [ 1 2 3 ] [ 2 3 4 5 ] ]
Recommended Posts:
- Can namespaces be nested in C++?
- Nested Classes in C++
- Decision Making in C / C++ (if , if..else, Nested if, if-else-if )
- Nested switch statement in C++
- C++ | Nested Ternary Operator
- list::pop_front() and list::pop_back() in C++ STL
- list::remove() and list::remove_if() in C++ STL
- list::empty() and list::size() in C++ STL
- list::emplace_front() and list::emplace_back() in C++ STL
- list::front() and list::back() in C++ STL
- list::push_front() and list::push_back() in C++ STL
- list::begin() and list::end() in C++ STL
- list unique() in C++ STL
- list end() function in C++ STL
- When do we use Initializer List in C++?
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.



