C++ Program to Illustrate Usage of List

This C++ program illustrates usage of list. The std::list class is a container that provides constant time insertion removal of elements from anywhere in the list but fast random access is not supported by list. This list supports bidirectional iteration and is usually implemented as a doubly linked list.

Here is the source code of the C++ program which illustrates usage of list. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to illustrate usage of list container
  3.  */
  4. #include <iostream>
  5. #include <list>
  6. using namespace std;
  7.  
  8. void printList(list<int> l)
  9. {
  10.     for(list<int>::const_iterator i = l.begin(); i != l.end(); i++)
  11.         cout << *i << " ";
  12.     cout << "\n";
  13. }
  14.  
  15. int main() {
  16.     list<int> l1 = {5, 2, 1, 10, 3, 4, 7, 6, 9, 8}, l2 = {13, 14, 12, 15};
  17.  
  18.     cout << "Unsorted List l1 : ";
  19.     printList(l1);
  20.     cout << "Unsorted List l2 : ";
  21.     printList(l2);
  22.     l1.sort();
  23.     cout << "Sorted List l1   : ";
  24.     printList(l1);
  25.     l2.sort();
  26.     cout << "Sorted List l2   : ";
  27.     printList(l2);
  28.     l1.merge(l2);
  29.     cout << "Merged List l1   : ";
  30.     printList(l1);
  31. }

$ gcc test.cpp
$ a.out
Unsorted List l1 : 5 2 1 10 3 4 7 6 9 8 
Unsorted List l2 : 13 14 12 15 
Sorted List l1   : 1 2 3 4 5 6 7 8 9 10 
Sorted List l2   : 12 13 14 15 
Merged List l1   : 1 2 3 4 5 6 7 8 9 10 12 13 14 15

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.