Thursday, 6 October 2016

C++ program to implement Sorting Container in STL


/*
Problem Statement: C++ program to implement Sorting Container in STL
Author: Pavan R Jaiswal

Options: 
  1: Add Element to List
  2: Display Sorted List
*/

#include "iostream"
#include "list"
#include "stdlib.h" // used for exit(0)

using namespace std;

class SortingContainerSTL{
 public:
  list<int> addElementToList(list<int>);
  void displaySortedList(list<int>);
};


list<int> SortingContainerSTL :: addElementToList(list<int> lt){
 
 int element;
 cout<<"\n Enter element: ";
 cin >> element;
 lt.push_back(element); // Add element at back
 cout<<"\nElement added to List\n";
 return lt;
}


void SortingContainerSTL :: displaySortedList(list<int> lt){
 list<int> :: iterator it;
 if(lt.empty()){
  cout<<"\nSorry. List is empty ";
 }else{
  lt.sort(); // sort the list
  cout<<"\nDisplaying sorted list: \n";
  for(it= lt.begin(); it != lt.end(); it++ ){
   cout<<"\t"<<*it;
  }
 }
}

int main(){
 SortingContainerSTL ob;
 int choice;
 char che;
 list<int> lt;
 do{
  cout<<"\n\t\t Sorting Container in STL\n";
  cout<<"\n1: Add Element To List";
  cout<<"\n2: Display Sorted List";
  cout<<"\n3: Exit";
  cout<<"\n Enter your choice: ";
  cin>>choice;
  switch(choice){
   case 1:
    lt = ob.addElementToList(lt);
   break;

   case 2:
    ob.displaySortedList(lt);
   break;

   case 3:
    exit(0);
   break;
   
   default:
    cout<<"\nInvalid choice. Try again";
   break; 
  
  }
  cout<<"\nDo you wish to continue [y/n]: ";
  cin>>che;
 }while(che == 'y' || che =='Y');
 return 0;
}

/*
 ####### OUTPUT ######
[pavan@localhost Programs]$ g++ SortingContainerSTL.cpp -o SortingOp
[pavan@localhost Programs]$ ./SortingOp 

   Sorting Container in STL

1: Add Element To List
2: Display Sorted List
3: Exit
 Enter your choice: 1

 Enter element: 23

Element added to List

Do you wish to continue [y/n]: y

   Sorting Container in STL

1: Add Element To List
2: Display Sorted List
3: Exit
 Enter your choice: 1

 Enter element: 25

Element added to List

Do you wish to continue [y/n]: y

   Sorting Container in STL

1: Add Element To List
2: Display Sorted List
3: Exit
 Enter your choice: 1

 Enter element: 10

Element added to List

Do you wish to continue [y/n]: y

   Sorting Container in STL

1: Add Element To List
2: Display Sorted List
3: Exit
 Enter your choice: 1

 Enter element: 2

Element added to List

Do you wish to continue [y/n]: y

   Sorting Container in STL

1: Add Element To List
2: Display Sorted List
3: Exit
 Enter your choice: 2

Displaying sorted list: 
 2 10 23 25
Do you wish to continue [y/n]: n
[pavan@localhost Programs]$ 


*/

No comments: