Christopher said:
Is my implementation correct to print only a blank line when the
following program is compiled and run?
#include <iostream>
#include <map>
int main()
{
std::map< const char *, std::string > m;
m["foo"]="bar";
std::cout << m["foo"] << std::endl;
return 0;
}
g++ prints "bar", which is of course the behavior I want. If this is
a(nother) problem with my implementation, what, if anything, can I do
to work around it?
This is not a problem with your library. The following code will yield a
blank line with g++, and I venture to say, on any standard complient
compiler:
#include <iostream>
#include <map>
int main()
{
char foo1 [4] = "foo";
char foo2 [4] = "foo";
std::map< const char *, std::string, std::less< const char * > m;
m[foo1]="bar";
std::cout << m[foo2] << std::endl;
return 0;
}
Back to your code:
std::map< const char *, std::string > m;
This is a bas idea: map operations will call operator< which is supposed to
be a weak total ordering. The standard makes no requirement that this holds
for comparision of const char *. Thus
std::map< const char *, std::string, std::less< const char * > m;
is better. However, it is clearly not what you want.
What happens is that your map m just stores a pointer to char and not a
copy of that string. Moreover, you donot compare the entries by their
values as strings but just by their address. Since foo1 and foo2 point to
different memory locations, the second programm prints a blank line. That
g++ prints "bar" for your code indicates that g++ folded the two occurences
of "foo" in your code to the same memory location: this tells us a little
bit about g++ handles string constants.
Recommendation: fix your code by using std::string for the keys in the map,
as well.
Best
Kai-Uwe