STL-List in C++ Programming


Lists are sequence containers that allow non-contiguous memory allocation.The include the header file to #include < list > . A list is a number of items in an ordered or unordered structure. A list can be used for a number of things like storing items or deleting and adding items

The program demonstrates the use of the STL List container in C++.

  • First, the program defines a function print which takes a list of integers as input and prints out each element separated by a space.
  • Next, the program creates two lists: a and b. a is initialized with the values 70, 20, 50, and 10, while b is initially empty. Elements are then added to b using the push_front and push_back member functions.
  • The program then demonstrates several member functions of the list container. front and back return the first and last elements of the list a respectively. empty returns true if the list is empty.
  • The program then demonstrates the reverse and sort member functions of the list container. reverse reverses the order of the elements in the list, while sort sorts the elements in ascending order.
  • Finally, the program returns 0 to indicate successful execution.

Source Code

#include<iostream>
#include<list>
using namespace std;
//STL-List in C++
void print(list<int> x){
    for(int o : x){
        cout<<" "<<o;
    }
    cout<<endl;
}
int main()
{
    list <int> a={70,20,50,10};
    print(a);
    list<int> b;
    b.push_front(150);
    b.push_front(250);
    b.push_back(350);
    print(b);
    cout<<"List First Element in A : "<<a.front()<<endl;
    cout<<"List Last  Element in A : "<<a.back()<<endl;
    cout<<"Empty or Not : "<<a.empty()<<endl;
    cout<<"Before Reverse : ";
    print(a);
    a.reverse();
    cout<<"After Reverse : ";
    print(a);
    cout<<"Before Sort : ";
    print(a);
    a.sort();
    cout<<"After Sort : ";
    print(a);
 
    return 0;
}
 

Output

 70 20 50 10
 250 150 350
List First Element in A : 70
List Last  Element in A : 10
Empty or Not : 0
Before Reverse :  70 20 50 10
After Reverse :  10 50 20 70
Before Sort :  10 50 20 70
After Sort :  10 20 50 70
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples