When you use the const char* as the key value, default map will compare the pointer, not the reference of the pointer.
So the result will be not our expectation.
Two solutions:
Use string as the key.
Provide the 3 parameters for the map declaration as in the following code.
#include <map>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
struct cmp_str
{
bool operator()(char const *a, char const *b)
{
return std::strcmp(a, b) < 0;
}
};
int main(int argc, const char* argv[])
{
printf("argv[1]:%s, length %d\n",argv[1],strlen(argv[1]));
DiagnosticVariableType type;
const char* p = argv[1];
const char* str = "BOOL";
printf("str:%s, length %d\n",str,strlen(str));
//map< string, int> TypeMap;
map< const char*, int, cmp_str> TypeMap;
TypeMap["BOOL"] = 100;
TypeMap["UDINT"] = 101;
printf("str:%s,value %d\n", str, TypeMap[str]);
printf("p:%s,value %d\n", p, TypeMap[p]);
return 0;
}
转载于:https://my.oschina.net/julian115/blog/468217