Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: List

📅 2011-Jan-04 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

A STL list in C++ provides the features of a doubly-linked list. Using the list is similar to using any other STL container, with iterators. Here is a simple example that illustrates the common list operations:

#include <list>
using namespace std;

typedef list<int>               IntList;
typedef IntList::iterator       IListIter;
typedef IntList::const_iterator IListCIter;

int main()
{
    IntList ilist;                                  // Empty list
    IntList ilist1( 100 );                          // List with 100 elements of 0
    IntList ilist2( 100, 3 );                       // List with 100 elements of 3
    IntList ilist3( ilist2.begin(), ilist2.end() ); // List copied from previous list

    // Create list: 10->20->30
    ilist.push_back( 10 );
    ilist.push_back( 20 );
    ilist.push_back( 30 );

    ilist.size();  // 3
    ilist.empty(); // false

    ilist.front(); // 10
    ilist.back();  // 30

    ilist.insert( ilist.begin(), 99 );          // 99 added, 99->10->20->30
    ilist.erase( ilist.begin() );               // 99 erased, 10->20->30
    ilist.erase( ilist.begin(), ilist.end() );  // Entire list erased

    return 0;
}