Sort number with STL list in c++

In mine previous article I have written a c++ program to sort a list of numbers but actually I do not need to do so because c++ already has the list class in it’s STL which we can use to sort a list of numbers.

#include <iostream>
#include <list>

using namespace std;

int main()
{
    int number;
    list<int> LIST_NUMBER;
    list<int>::iterator iter;

    while (true)
    {
        cout << "Enter number (ENTER -1 to exit): ";
        cin >> number;
        if (number == -1)
        {
            break;
        }
        LIST_NUMBER.push_back(number);
    }

    LIST_NUMBER.sort(); // Sort the numbers

    for (iter = LIST_NUMBER.begin(); iter != LIST_NUMBER.end(); iter++)
    {
        cout << *iter << endl;
    }
    
    return 0;
}

With the list class we have saved lots of time writing our own code to perform the same job!

Like this post? Kindly share!