Contents
List
A list is also a sequential container similar to a vector but allows for insertions and deletions in a more efficient manner.File: list1.cpp
// C++ program to demonstrate the use of list containers #include <iostream> #include <list> using namespace std; int main() { // defining list list<int> list1 ; for( int i1=1 ; i1<=5 ; i1++ ) { list1.push_back( i1 ) ; } list1.push_front( 6 ) ; list1.insert( list1.begin() , 14 ) ; list<int>::iterator it = list1.begin() ; advance(it, 2) ; list1.insert( it , 15 ) ; for (it = list1.begin() ; it != list1.end() ; it++ ) { cout << *it << ' '; } cout << endl ; return 0; } $ g++ list1.cpp ; ./a.exe 14 6 15 1 2 3 4 5
Exercise
File: list_ex1.cpp
// C++ program to demonstrate the use of list containers #include <iostream> #include <list> using namespace std; int main() { // We have a list 1 containing 6 elements //Take the elements out of list 1 and insert them into list 2 //so that the elements in list 2 are sorted. //Do not use a library STL sort function. //Iterate throught the list1 elements and insert into //list2 one element at a time by finding the correct //position for it. //4 2 3 5 1 16 //Take 4 out and put it in list2 // Take 2 out and place it before 4 in list2 list<int> list1 ; list<int> list2 ; list1.push_back( 4 ) ;list1.push_back( 2 ) ; list1.push_back( 3 ) ;list1.push_back( 5 ) ; list1.push_back( 1 ) ; list1.push_back( 16 ) ; list<int>::iterator it = list1.begin() ; list<int>::iterator it2 = list2.begin() ; for( int a1 : list1 ) { cout << a1 << " " ; } cout << endl ; return 0; }
File: list_ex1_s.cpp