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

后端 未结 3 1538
天命终不由人
天命终不由人 2020-12-14 15:33

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.<

相关标签:
3条回答
  • 2020-12-14 16:25
    map<string, int> *myFruit;
    (*myFruit)["apple"] = 1;
    (*myFruit)["pear"] = 2;
    

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

    0 讨论(0)
  • 2020-12-14 16:29

    You can do this:

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

    or

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

    or

    map<string, int> &tFruit = *myFruit;
    tFruit["apple"] = 1;
    
    0 讨论(0)
  • 2020-12-14 16:37

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

    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>() ;
    
    0 讨论(0)
提交回复
热议问题