简体   繁体   中英

Pointer to a map

If I define a pointer-to- map like this:

map<int, string>* mappings;

mappings is a pointer. How should I use this pointer to operate the map?

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!

(Though this equivalence doesn't hold for access-by-index like (*a)[b] , for which you may not use the -> syntax.)

Not much difference except that you have to use -> for accessing the map members. ie

mapping->begin() or mapping->end()

If you don't feel comfortable with that then you can assign a reference to 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. ie

myMap[2] = "2";
myMap.begin() or myMap.end();

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;
}

With the introduction of "at" function in c++ 11, you can use mappings->at(key) instead of (*mapping)[key] .

Keep in mind that this api will throw out_of_range exception if the key is not already available in the map.

另一种使用指针的好方法,我喜欢调用 mappings->(以及你想调用的函数)

好吧,STL 旨在降低指针处理的复杂性..所以更好的方法是使用 stl::iterator.. 尽量避免指针:-/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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