[Container List ]Linked List in C++

 


#include <iostream>
#include <list>

class Car {
  int num_;
  std::string str_;
  public:
      Car(int no, std::string data) : num_(no), str_(data) {}
      int getNum() { return num_; }
      std::string getStr() { return str_; }
}; 

int main()
{
    Car c1(73, "Benz");
    std::list<Car> sll;
    
    auto printList = [&]() {
      for (Car sl: sll) {
           std::cout << sl.getNum() << " = " << sl.getStr() << " -> ";
      }      
      std::cout << std::endl;
    };

    /* Repeatedly want to insert the 
       same element. Eg: first parameter
       2 represents, c1 will be 
       inserted twice. */
    sll.assign(2, c1);
    printList();
    
    /* Insert a head element. */
    Car c2(89, "Cooper");
    auto it = sll.begin();
    if (it != sll.end()) {
        sll.insert(it, c2);
    }
    printList();
    
    /* Insert an element in the beginning */
    Car c3(81, "Audi");
    sll.push_front(c3);
    printList();
    
    Car c4(90, "Range Rovers");
    /* Insert in the middle somewhere by index */
    auto it2 = sll.begin();
    std::advance(it2, 1); // 1 is the index
    if (it2 != sll.end()) {
        sll.insert(it2, c4);
    }
    printList();
    
    /* Insert an element at the end */
    Car c5(88, "Tata");
    sll.push_back(c5);
    printList();
    
    /* Remove the element from the end. */
    sll.pop_back();
    printList();
    
    /* Remove the element from the front. */
    sll.pop_front();
    printList();
    
    auto it3 = sll.begin();
    std::advance(it3, 2); // 1 is the index
    sll.erase(it3);
    printList();
    
    /* Remove range of elements 
       from it4 and before it5 */
    auto it4 = sll.begin();
    auto it5 = sll.begin();
    std::advance(it5, 2);
    
    sll.erase(it4, it5);
    printList();
    return 0;
}

Output:

1
2
3
73 = Benz -> 73 = Benz -> 
89 = Cooper -> 73 = Benz -> 73 = Benz -> 
81 = Audi -> 89 = Cooper -> 73 = Benz -> 73 = Benz -> 
81 = Audi -> 90 = Range Rovers -> 89 = Cooper -> 73 = Benz -> 73 = Benz -> 
81 = Audi -> 90 = Range Rovers -> 89 = Cooper -> 73 = Benz -> 73 = Benz -> 88 = Tata -> 
81 = Audi -> 90 = Range Rovers -> 89 = Cooper -> 73 = Benz -> 73 = Benz -> 
90 = Range Rovers -> 89 = Cooper -> 73 = Benz -> 73 = Benz -> 
90 = Range Rovers -> 89 = Cooper -> 73 = Benz -> 
73 = Benz -> 

Click here to debug.

Comments