如何获得地图价值的参考?

时间:2018-07-09 13:08:22

标签: c++ stl

通常std :: map :: operator []返回对该对象的引用。

https://en.cppreference.com/w/cpp/container/map/operator_at

std::map<char*, char*>* myMap1 = new std::map<char*, char*>() ;
char* c1 = new char[100];
strcpy(c1,"fggf");
char* c2 = new char[100];
strcpy(c2 ,"gdgfd");
myMap1->insert(std::pair<char*,char*>(c1,c2));
char* v1=  (*myMap1)[c1];
char** v2=  &(*myMap1)[c1];

在此程序中(* myMap1)[c1]未返回引用,为什么仅此语法&(* myMap1)[c1]返回参考为何?

2 个答案:

答案 0 :(得分:1)

C ++和C最好不要混用! 当您可以使用字符串(如果您使用C ++ 17或string_view)时,请不要使用char *

map<string, string> myMap; //C++ prefers value sementatics, don't go for pointers 
                            //unless absolutely necessary, and if it is...
auto myMapPtr = make_unique<map<string, string>>(); //Use smart pointers! 
myMap["fggf"] = "gdgfd"; //Lots of people don't know that [] also inserts, no need to construct a pair...

string c2 = MyMap.at("fggf"); //that's it!

就是这样,您只需要三行即可。不要感到困惑。 :)

答案 1 :(得分:1)

我支持上面的答案,但是如果您坚持使用,请使用以下命令:

std::map<const char*, const char*>* myMap1 = new std::map<const char*, const char*>();
const char* c1 = "fggf";
const char* c2 = "gdgfd";
myMap1->insert(std::pair<const char*,const char*>(c1,c2));
const char* v1=  myMap1[c1];
const char** v2=  &(myMap1[c1]);