简体   繁体   English

C++ map::find char * 与 char []

[英]C++ map::find char * vs. char []

I'm using C++ map to implemented a dictionary in my program.我正在使用 C++ map 在我的程序中实现字典。 My function gets a structure as an argument and should return the associated value based on structure.name member which is char named[32] .我的 function 获取一个结构作为参数,并且应该返回基于structure.name成员的关联值,该成员是char named[32] The following code demonstrates my problem:以下代码演示了我的问题:

map <const char *, const char *> myMap;
myMap.insert(pair<const char *, const char *>("test", "myTest"));

char *p = "test";
char buf[5] = {'\0'};
strcpy(buf, "test");

cout << myMap.find(p)->second << endl; // WORKS
cout << myMap.find("test")->second << endl; // WORKS
cout << myMap.find(buf)->second << endl; // DOES NOT WORK

I am not sure why the third case doesn't work and what should I do to make it work.我不确定为什么第三种情况不起作用,我应该怎么做才能让它起作用。 I debugged the above code to watch the values passed and I still cannot figure the problem.我调试了上面的代码以观察传递的值,但我仍然无法解决问题。

Thanks!谢谢!

Pointer comparison, not string comparison, will be performed by map to locate elements. map将执行指针比较,而不是字符串比较来定位元素。 The first two work because "test" is a string literal and will have the same address.前两个之所以有效,是因为"test"是一个字符串文字,并且具有相同的地址。 The last does not work because buf will not have the same address as "test" .最后一个不起作用,因为buf将不会有与"test"相同的地址。

To fix, either use a std::string or define a comparator for char* .要修复,请使用std::string或为char*定义比较器。

The map key is a pointer, not a value. map 键是一个指针,而不是一个值。 All your literal "test" strings share storage, because the compiler is clever that way, so their pointers are the same, but buf is a different memory address.您所有的文字“测试”字符串都共享存储空间,因为编译器在这方面很聪明,所以它们的指针是相同的,但buf是一个不同的 memory 地址。

You need to use a map key that has value equality semantics, such as std::string , instead of char* .您需要使用具有值相等语义的 map 键,例如std::string ,而不是char*

Like was mentioned you are comparing on the address not the value.就像提到的那样,您正在比较地址而不是价值。 I wanted to link this article:我想链接这篇文章:

Is a string literal in c++ created in static memory? c++中的字符串文字是在static memory中创建的吗?

Since all the literals had the same address this explains why your comparison of string literals worked even though the underlying type is still a const char * (but depending on the compiler it may not ALWAYS be so)由于所有文字都具有相同的地址,这就解释了为什么即使底层类型仍然是const char * ,你对字符串文字的比较仍然有效(但取决于编译器,它可能并非总是如此)

Its because by buf[5] you are allocating the memory pointed by buf but when u use 'p' pointer it points to the same memory location as used by map. So always use std::string in key instead of pointer variable.这是因为通过 buf[5],您正在分配 buf 指向的 memory,但是当您使用“p”指针时,它指向与 map 使用的相同的 memory 位置。因此始终在键中使用 std::string 而不是指针变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM