To strictly answer your question, Joachim Pileborg's answer is the way to go:
std::list<std::list<double> >::iterator it = list.begin();
std::advance(it, 3);
std::list<double>::iterator it2 = (*it).begin();
std::advance(it2, 3);
double d = *it2;
Now, from your question and further comments it is not clear whether you always add elements to the end of the lists or they can be added anywhere. If you always add to the end, vector<double>
will work better. A vector<T>
does not need to be copied every time its size increases; only whenever its capacity increases, which is a very different thing.
In addition to this, using reserve()
, as others said before, will help a lot with the reallocations. You don't need to reserve for the combined size of all vectors, but only for each individual vector. So:
std::vector<std::vector<double> > v;
v.reserve(512); // If you are inserting 400 vectors, with a little extra just in case
And you would also reserve for each vector<double>
inside v
. That's all.
Take into account that your list of lists will take much more space. For each double
in the internal list, it will have to allocate at least two additional pointers, and also two additional pointers for each list inside the global least. This means that the total memory taken by your container will be roughly three times that of the vector. And all this allocation and management also takes extra runtime.
vector
. Uselist
only when you need to splice. – Evalynevanvector::reserve
to reserve the memory and avoid extra copies if that is your concern. Also, even though you can getoperator[]
for what you want, it will be really inefficient. – Organizationstd::vector
is usually pretty smart when it needs to reallocate, so the bigger it gets the less it has to reallocate and copy.std::list
is only faster if you are creating the container many many times during the lifetime of the program. – Rooted