list::back, list::front (STL Sample)

The sample code below illustrates how to use the list::back and list::front STL functions in Visual C++.

Required Header:
<list>

Prototype:

     reference back();
     const_reference back() const;
     reference front();
     const_reference front() const;
     void pop_back();
     void pop_front();
     void push_back(const T& x);
     void push_front(const T& x);

Note: The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.

Description:
The member function back returns a reference to the last element of the controlled sequence. The member function front returns a reference to the first element of the controlled sequence. The member function pop_back removes the last element of the controlled sequence. The member function pop_front removes the first element of the controlled sequence. All the above functions require that the controlled sequence be non-empty. The member function push_back inserts an element with value x at the end of the controlled sequence. The member function push_front inserts an element with value x at the beginning of the controlled sequence.

Sample Code:

//////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// liststck.cpp :  This example shows how to use the various stack
//                 like functions of list.
//
// Functions:
//
//    list::back
//    list::front
//    list::pop_back
//    list::pop_front
//    list::push_back
//    list::push_front
//////////////////////////////////////////////////////////////////////

#include <list>
#include <string>
#include <iostream>

using namespace std ;

typedef list<string> LISTSTR;

void main()
{
    LISTSTR test;

    test.push_back("back");
    test.push_front("middle");
    test.push_front("front");

    // front
    cout << test.front() << endl;

    // back
    cout << test.back() << endl;

    test.pop_front();
    test.pop_back();

    // middle
    cout << test.front() << endl;
}

 

Program Output is:

front
back
middle