Accessing elements of a list of lists in C++

oaktree picture oaktree · Sep 5, 2012 · Viewed 16.2k times · Source

I have a list of lists like this:

    std::list<std::list<double> > list;

I filled it with some lists with doubles in them (actually quite a lot, which is why I am not using a vector. All this copying takes up a lot of time.)

Say I want to access the element that could be accesed like list[3][3] if the list were not a list but a vector or two dimensional array. How would I do that?

I know that accessing elements in a list is accomplished by using an iterator. I couldn't figure out how to get out the double though.

Answer

ecatmur picture ecatmur · Sep 5, 2012
double item = *std::next(std::begin(*std::next(std::begin(list), 3)), 3);

Using a vector would usually have much better performance, though; accessing element n of a list is O(n).

If you're concerned about performance of splicing the interior of the container, you could use deque, which has operator[], amortized constant insertion and deletion from either end, and linear time insertion and deletion from the interior.

For C++03 compilers, you can implement begin and next yourself:

template<typename Container>
typename Container::iterator begin(Container &container)
{
    return container.begin();
}
template<typename Container>
typename Container::const_iterator begin(const Container &container)
{
    return container.begin();
}
template<typename T, int n>
T *begin(T (&array)[n])
{
    return &array[0];
}

template<typename Iterator>
Iterator next(Iterator it, typename std::iterator_traits<Iterator>::difference_type n = 1)
{
    std::advance(it, n);
    return it;
}