Re: STL map and char * problems
Digital Puer wrote:
I am having a problem with the STL map and char *.
I'm on Linux and am using g++ 4.1.2.
I am using two STL maps:
1. map<char *, int>
2. map<string, int>
For some reason, when I insert the same char strings and
then iterate over them, the map from (1) will not print the
keys in the expected lexical (alphabetical) order, but the
map from (2) will print the keys in order. I would prefer
to use map (1).
Here is a program that demonstrates this problem.
map<char *, int> keyCountsChar;
keyCountsChar["bbtman"] = 1;
keyCountsChar["batman"] = 1;
keyCountsChar["aorta"] = 1;
keyCountsChar["dude"] = 1;
printf("content of keyCountsChar:\n");
for (map<char *, int>::iterator iter = keyCountsChar.begin();
iter != keyCountsChar.end();
iter++)
{
printf("%s --> %d\n", iter->first, iter->second);
}
map<string, int> keyCountsString;
keyCountsString["bbtman"] = 1;
keyCountsString["batman"] = 1;
keyCountsString["aorta"] = 1;
keyCountsString["dude"] = 1;
printf("content of keyCountsString:\n");
for (map<string, int>::iterator iter = keyCountsString.begin();
iter != keyCountsString.end();
iter++)
{
printf("%s --> %d\n", iter->first.c_str(), iter->second);
}
The output is:
content of keyCountsChar:
bbtman --> 1
batman --> 1
aorta --> 1
dude --> 1
content of keyCountsString:
aorta --> 1
batman --> 1
bbtman --> 1
dude --> 1
As you can see, the map with the string iterates over the
keys in the correct lexical order, but the maps with the char *
does not.
Can someone please help me out? I would like to use
the map with the char * and still iterate in lexical order.
With the char* version, you're sorting on the addresses stored in the
pointers, not on the strings they're pointing at. To be honest you're
much better off just using the std::string version, but if you have good
reasons for wanting the char* one then you can use an appropriate
comparison predicate as follows:
#include <algorithm>
#include <cstring>
#include <iostream>
#include <map>
struct Pred
{
bool operator()(const char *lhs, const char *rhs) const
{
return strcmp(lhs, rhs) < 0;
}
};
int main()
{
typedef std::map<const char*,int,Pred> MapType;
MapType m;
m["lalala"] = 84;
m["wibble"] = 9;
m["blah"] = 23;
for(MapType::const_iterator it=m.begin(), iend=m.end(); it!=iend; ++it)
{
std::cout << it->first << ' ' << it->second << '\n';
}
return 0;
}
HTH,
Stu