On 5$B7n(B19$BF|(B, $B>e8a(B1$B;~(B00$BJ,(B, Neelesh <neelesh.bo...@gmail.com> wrote:
On May 18, 11:16 am, blackbiscuit <infozyzh...@gmail.com> wrote:
On 5$B7n(B18$BF|(B, $B2<8a(B3$B;~(B48$BJ,(B, Ian Collins <ian-n...@hotmail.com> wrote:
blackbiscuit wrote:
Dear all,
Now I am confused by a problem. I have defined a map object.
map< const char*, int > maps;
then I add one value into maps.
maps[ "June" ] = 1;
Later, I have another char*.
char* p = "June";
And I have maps[ p ] == 1.
Seems it is trivial. But my problem is the key of maps is const char*
which is a pointer. How can map find the key? Does p has the same
address as the constant "June"?
It can't, unless you use the exact same string literal.
Use std::string for your key.
--
Ian Collins
Seems I got the answer. The C++ compiler first creates the "June" as a
constant string on the stack. And then the pointer p is pointed to
that constant string. So, now the "June"'s address is as similar as p.
Whether all string literals are distinct or not is implementation
dependent. Which effectively means that
int main()
{
const char* p = "June";
const char* q = "June";
bool eq = p == q;
}
Whether "eq" is true or false is implementation dependent. so in the
current case whether map[p] will be same as map["June"] is
implementation dependent. Not just that, even the output of following
code is implementation dependent
#include <map>
#include <iostream>
int main()
{
std::map<const char*, int> m;
m["June"] = 5;
std::cout << m["June"] << std::endl; //Is the string literal
"June" on this line same as string literal "June" on the previous
line? Implementation dependent.
}
So it means to use map in that way is quite dangerous. Is there any