C++ 指向地图的指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7482888/
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
Pointer to a map
提问by Lightness Races in Orbit
If I define a pointer-to-map
like this:
如果我map
像这样定义一个指针:
map<int, string>* mappings;
mappings
is a pointer. How should I use this pointer to operate the map?
mappings
是一个指针。我应该如何使用这个指针来操作地图?
回答by Lightness Races in Orbit
Use the pointer just like you use any other pointer: dereference it to get to the object to which it points.
使用指针就像使用任何其他指针一样:取消引用它以获取它指向的对象。
typedef std::map<int, string>::iterator it_t;
it_t it1 = mappings->begin(); // (1)
it_t it2 = (*mappings).begin(); // (2)
string str = (*mappings)[0]; // (3)
Remember that a->b
is — mostly — equivalent to (*a).b
, then have fun!
请记住,这a->b
- 主要 - 相当于(*a).b
,然后玩得开心!
(Though this equivalence doesn't hold for access-by-index like (*a)[b]
, for which you may not use the ->
syntax.)
(虽然这种等价性不适用于像 那样按索引访问(*a)[b]
,您可能不使用->
语法。)
回答by iammilind
Not much difference except that you have to use ->
for accessing the map
members. i.e.
除了您必须->
用于访问map
成员之外,没有太大区别。IE
mapping->begin() or mapping->end()
If you don't feel comfortable with that then you can assign a referenceto that and use it as in the natural way:
如果您对此感到不舒服,那么您可以为其分配一个引用并以自然的方式使用它:
map<int, string> &myMap = *mappings; // 'myMap' works as an alias
^^^^^^^^
Use myMap
as you generally use it. i.e.
用myMap
你一般使用它。IE
myMap[2] = "2";
myMap.begin() or myMap.end();
回答by Nicola Musatti
For instance:
例如:
#include <map>
#include <string>
#include <iostream>
int main() {
std::map<int, std::string> * mapping = new std::map<int, std::string>();
(*mapping)[1] = "test";
std::cout << (*mapping)[1] <<std::endl;
}
回答by ofir
another nice way of using pointers, which I like is calling mappings->(and the function you want to call)
另一种使用指针的好方法,我喜欢调用 mappings->(以及你想调用的函数)
回答by Aman Agarwal
Well, STL is designed to reduce the complexity of pointer handling..so better approach is to use stl::iterator.. try to avoid pointers :-/
好吧,STL 旨在降低指针处理的复杂性..所以更好的方法是使用 stl::iterator.. 尽量避免指针:-/