如何从指针访问 C++ 映射的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1236485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:16:08  来源:igfitidea点击:

How to access elements of a C++ map from a pointer?

c++

提问by Greg Hewgill

Simple question but difficult to formulate for a search engine: if I make a pointer to a map object, how do I access and set its elements? The following code does not work.

一个简单的问题,但很难为搜索引擎制定:如果我创建一个指向地图对象的指针,我如何访问和设置它的元素?以下代码不起作用。

map<string, int> *myFruit;
myFruit["apple"] = 1;
myFruit["pear"] = 2;

回答by Greg Hewgill

You can do this:

你可以这样做:

(*myFruit)["apple"] = 1;

or

或者

myFruit->operator[]("apple") = 1;

or

或者

map<string, int> &tFruit = *myFruit;
tFruit["apple"] = 1;

回答by swongu

myFruitis a pointer to a map. If you remove the asterisk, then you'll have a map and your syntax following will work.

myFruit是一个指向地图的指针。如果您删除星号,那么您将拥有一张地图,并且您的语法将起作用。

Alternatively, you can use the dereferencing operator (*) to access the map using the pointer, but you'll have to create your map first:

或者,您可以使用解引用运算符 ( *) 通过指针访问地图,但您必须先创建您的地图:

map<string, int>* myFruit = new map<string, int>() ;

回答by rpjohnst

map<string, int> *myFruit;
(*myFruit)["apple"] = 1;
(*myFruit)["pear"] = 2;

would work if you need to keep it as a pointer.

如果您需要将其保留为指针会起作用。