I need a container of containers like:
class Widget {
...
};
...
std::vector<std::list<Widget> > widgets;
Because STL containers copy objects in them, and copy a container is not a cheap operation, I think this container of containers may leads to really bad efficiency and therefore a bad design.
I want to know if I am right. And if it is, should I use container of container pointers or something else?
Thanks
p.s.
Thanks for you guys, and now I know whether it’s a bad design or not depends on how I use it.
So if I know how many list(at most) would be inserted into vector and then use vector::reserve to avoid vectorreallocation and after that I just query about objects in it, this may be a good design.
On the other hand, if I need insert list into the vector every now and then, this may leads to really bad efficiency.
Am I right?
It is not bad design. It is the way you use it that can be bad design. If your code requires frequent deep copying and you implement
std::vector<std::list<Widget> *> widgets, but still require a deep copy, there isn’t much difference with what you are doing.If for example, you are querying some member of the
lists in the vector very frequently, this may actually be good design because of the memory proximity due to the compactness of the vector.Modern compilers with C++11 support that has move semantics usually move data instead of copying data. So I will not be too concerned about vector relocation or shifting. ‘Moving’ can still be done by older compilers using
std::swapwhenever it makes more sense than copying.