Re: querry related to STL map..
RenjithMohan wrote:
char *p = new char[3];
Here you are wrong. In order to have "May" you need size 4 to
accomodate the null terminator.
strcpy(p, "May");
int it = m1[p]; // returns 0 .. instead of 31 ....
Basically your comparator for the map is wrong. string
literals have the same type and may be ordered according to
the < operator. For char*, the default less<> comparator is
no longer acceptable..
The correct way to order the keys, if it is char* is to have a
custom comparator for the map.
template<class _Ty>
struct comp_function
: public binary_function<_Ty, _Ty, bool>
{ // functor for operator<
bool operator()(const _Ty& _Left, const _Ty& _Right) const
{ // apply strcmp to operands
return (strcmp(_Left, _Right)< 0);
}
};
Just one question: why on earth do you make this a template,
since it will fail to instantiate unless _Ty is char* or char
const*?j
//Notice how we have given our comparator
map<char *,int, comp_function<char*> > m1;
And there is still one problem left:
m1.begin()[ 0 ] = 'z' ;
Looks fine to me, and the compiler won't complain. But
supposing the initializations below, I rather doubt that
m1["zanuary"] will return 31 after this.
The obvious solution is to simply write:
map< std::string, int > m1 ;
and be done with it. If you really insist on C style strings,
then at the very least:
map< char const*, int, comp_function > m1 ;
--
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! ]