C++: List

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;
}

Python: __lt__()

If you try to sort a list of objects of your own class …

class Foobar:
    def __init__(self, idx):
        self.idx = idx
        return

fooList = [Foobar(10), Foobar(2)]
fooList.sort()

… you get a TypeError error:

TypeError: unorderable types: Foobar() < Foobar()

Python is reporting that it does not know how to compare Foobar objects.

Define a __lt__() method in the Foobar class. This rich comparison method is preferred over the generic __cmp__() method.

class Foobar:
    def __lt__(self, other):
    """Less-than comparison."""
    return self.idx < other.idx