Is the container of containers bad design?
I need a container with containers like:
class Widget {
...
};
...
std::vector<std::list<Widget> > widgets;
Since STL containers copy objects into them, and copying a container is not a cheap operation, I think that this container of containers could lead to really bad efficiency and hence bad design. I want to know if I'm right. And if so, should I use a container of container pointers or something else? Thanks to
ps
Thank you guys and now I know whether the design is bad or not depends on how I use it.
So if I know how much list
(at most) will be inserted into vector
and then use vector::reserve
to avoid reallocation vector
, and after that I just query about the objects in it, that might be good design.
On the other hand, if I have to insert list
from vector
time to time, it can lead to really poor performance.
I'm right?
source to share
It's a pretty good design. This is how you use it, which could be bad design. If your code requires frequent deep copying and you are implementing std::vector<std::list<Widget> *> widgets
but still need deep copying, there isn't much difference in what you do.
If, for example, you ask for some term list
in a vector very often , this might be a really good design because of the proximity of memory due to the compactness of the vector.
Modern C ++ 11-enabled compilers that have move semantics tend to move data instead of copying data. So I won't worry too much about wrapping or wrapping the vector. "Moving" can still be done by older compilers using std::swap
, when it makes more sense, than copying.
source to share
I believe the answer to your design question mostly depends on the specifics of your project, which we don't see. Do you need to store values (and manage widget lifetime) or just links?
Note that std :: vector only copies copies when copying a vector. Otherwise, when you need to increase the capacity of the vector, it uses elements that move constructors, which are usually cheap.
source to share