//
// main.cpp
// Lists (STL)
//
// Created by Himanshu on 18/09/21.
//
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
// comparator to compare only integral part:
bool comparator (double first, double second) {
return ( int(first) < int(second) );
}
void printIntList (list<int> l) {
list<int>::iterator it;
for (it = l.begin(); it != l.end(); it++) {
cout<<(*it)<<" ";
}
cout<<endl;
}
void printFloatList (list<float> l) {
list<float>::iterator it;
for (it = l.begin(); it != l.end(); it++) {
cout<<(*it)<<" ";
}
cout<<endl;
}
int main () {
// Declaration
list<float> first, second;
// Initialisation
list<int> myListFirst({10, 20, 15});
// myListSecond is intialised with 3 ints
// having value as 45
list<int> myListSecond(3, 45);
cout<<"myListFirst elements:"<<endl;
printIntList(myListFirst);
cout<<"myListSecond elements:"<<endl;
printIntList(myListSecond);
myListFirst.swap(myListSecond);
cout<<"myListFirst elements after swap:"<<endl;
printIntList(myListFirst);
cout<<"myListSecond elements after swap:"<<endl;
printIntList(myListSecond);
myListFirst.unique();
cout<<"myListFirst elements after unique:"<<endl;
printIntList(myListFirst);
myListFirst.clear();
cout<<"myListFirst elements after clear:"<<endl;
printIntList(myListFirst);
if (myListFirst.empty()) {
cout<<"myListFirst is empty"<<endl;
}
first.push_back (3.1);
first.push_back (1.2);
first.push_back (5.9);
cout<<"first list elements:"<<endl;
printFloatList(first);
second.push_back (3.7);
second.push_back (7.8);
second.push_back (1.2);
cout<<"second list elements:"<<endl;
printFloatList(second);
//sort method of lists sorts the data in increasing order of elements. list sort is different from algorithm sort
first.sort();
second.sort();
cout<<"first list elements after sort():"<<endl;
printFloatList(first);
cout<<"second list elements after sort():"<<endl;
printFloatList(second);
// merge method removes all the elements in second,
// and inserts them into their ordered (sorted) position within first
// provided both are sorted
first.merge(second);
cout<<"first list elements after merge:"<<endl;
printFloatList(first);
// second is now empty after merge
if (second.empty()) {
cout<<"List second is empty after merge"<<endl;
}
second.push_back(3.1);
second.push_back(2.8);
second.push_back(3.5);
// Merge using a custom comparator which only
// merge according to the relation specified
first.sort();
second.sort();
first.merge(second, comparator);
// Custom comparator compares only integer part
// hence 3.1 is after 3.7
std::cout << "first list after custom merge:"<<endl;
printFloatList(first);
return 0;
}