Re: C++ STL container of containers
Is it legal to have an STL container containing another STL container?
Of course. As long as the type meets the formal requirements for
container elements (and all of the STL containers do).
Of course, you might want to think about the performance implications
such cases. If you have an std::vector< std::map< T1, T2 > >, with a
couple of thousand elements, and each map also contains a couple of
thousand elements, there's likely to be a noticeable pause when a
push_back requires a new allocation:-). But I wouldn't hesitate for
smaller containers, and in fact, have done it on a couple of occasions.
The most obvious examples, of course, are where the nested container is
an std::string -- std::map< std::string, X > is fairly common in my
code, as is std::vector< std::string >. But I've also got an
std::map< std::string, std::set< std::string > >
, for example. (In general, node based containers like map, set and
list at the outer level avoid most of the performance issues.)
More specifically, I'd like to have a map where each pair consists of
a unique string key and a vector of unsigned ints.
If so, are their any good examples online. I've looked at lots of
sites and books and all the examples have been of containers using
primitive data types.
Are you sure you've never seen an std::map with std::string as the key
The only particularity, except for the possible performance issues, is
slight quirck of C++ syntax: two >> without an intervening space is a
single shift right token, and does NOT close two nested template
parameter lists, so even if you prefer not to use spaces on the inside
edges of a <>, you'll need to separate them here, e.g.:
std::map<std::string, std::vector<int> > ...
(Personally, I think a space after the < and before the > improves
readability anyway, and would systematically write:
std::map< std::string, std::vector< int > > ...
.. The result is that I've never actually been bitten by this
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]