Re: Why can't I insert or delete the inside element of set<set<string>>?
Rain Ma wrote:
Hi, I was using the STL set as follows and what I want to do here is to
change mySet from {{"Hi", "Hello world to"}, {"A", "B"}} to {{"Hello
world to"},{"A","B"}}, but it fails to compile. Why? And how can I
manage to achieve my goal?Thanks.
====================================================================================
#include <iostream>
#include <set>
#include <string>
using std::set;
using std::string;
void func()
{
set< set<string> > mySet;
....// Initializing mySet, and it is like {{"Hi", "Hello world
to"}, {"A", "B"}}
set< set<string> >::iterator iter = mySet.begin();
iter->erase("Hi"); //There is a complile error here
}
A std::set stores objects by a "key" value - which in the case of a
std::set is the stored object itself. And in order for std::set to
maintain its contents in sorted order, the key values themselves must
be const. Otherwise, a program would be able to change a key value
without informing the std::set - and its contents would no longer be in
sorted order.
So in the example code: each set of strings is a key in a set, and
since keys in a set must be const, it then follows that each set of
strings is itself const. The const-ness of the set causes the error -
because it is not legal to erase or add items to a const set. Note that
the program is still free to erase and replace any of the sets of
strings on an individual basis. In other words, to erase the string
"Hi" from one of the set of strings, the program would have to make a
copy of the set - remove the string "Hi" - and then replace the
existing set with the modified copy - all in all not a particularly
convenient workaround to say the least.
A set of sets generally has little practical value - especially since
the order of the contained sets is neither very clear nor particularly
useful. Therefore using a different kind of container to the hold the
sets of strings, say, a std::vector, is probably the more workable
design.
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]