Re: map parameters
On Mar 18, 6:16 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
pk_pk wrote:
why is it that i am allowed to use a class or a struct for
the "value" part in a map, but not for the "key" in the
pair?
You can, but not just any class will do. There are requirements.
i can do this (where CMaterial is a struct) :
typedef std::map<std::string, CMaterial> MatAttr;
but i can't do:
typedef std::map<CMaterial, CMaterial> Stuff;
i realize i can do this:
typedef std::map<CMaterial*, CMaterial> Stuff;
i'm curious to know why the "key" has to be a fundamental datatype
like a pointer, float, etc.
It does not have to be a fundamental datatype. Note that you
already used std::string as a key.
The requirements for the type to be used as a key are (off the
top of my head):
a) KeyType has to be copy-constructible.
At least at present, it also has to be assignable. (I don't
think that any implementation actually requires the assignment,
except to fulfill a concept check, and I vaguely seem to
remember hearing that this requirement will be dropped in the
future.)
b) std::less<KeyType> has to be defined. The standard way of achieving tha=
t
is to have KeyType provide an operator<.
I suspect that it's more idiomatic for the user to provide a
custom comparison operator to the map. (It really depends on
the class, of course. If an operator< makes sense in general,
then you provide it. If it doesn't, however, you don't provide
one just for std::map---you define some sort of comparison type
which you specify explicitly.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=EF=BF=BDe objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=EF=BF=BDmard, 78210 St.-Cyr-l'=EF=BF=BDcole, France, +33 (0)1 30 2=
3 00 34