P
P
pr0fedt2012-05-30 16:42:40
C++ / C#
pr0fedt, 2012-05-30 16:42:40

Bug with std::map or what am I doing wrong?

Greetings,
Please help me, I encountered an incomprehensible behavior of std:: map in MSVC 2010
, for example, I will give the following code:

#include <map>
#include <stdio.h>
#include <Windows.h>

int main()
{
  std::map<char*,int> MAP;
  MAP["a"] = 42;
  char key[10];
  scanf("%s",&key);
  printf("%s:%d\n",key,MAP[key]);
  printf("%d",MAP["a"]);
  system("pause");
}

if we try to get a map element with a key obtained, for example, from the standard input stream (we take the predefined one in the “a” code), we get that it is a completely different element, but at the same time (strcmp(key, “a”) = = 0), while it can be taken into account, of course, that "a" has the type const char *, but even MAP[(char *)"a"] does not give the desired result, CHADNT?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gribozavr, 2012-05-30
@pr0fedt

Your map key is a pointer, not a string. Use std::string as the key, or write a custom comparator for map.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question