How do I dereference myMaps?
The same way you dereference any other pointer. Exactly as you are doing in (*testMap)[1] = 1;
This does not work.
No, it doesn't, but this does:
test->myMaps = testMap;
std::cout << (*(test->myMaps))[1] << std::endl;
// or cleaner:
// std::cout << (*test->myMaps)[1] << std::endl;
// due to operator precedence...
Note the extra parenthesis around the pointer before invoking map::operator[] on the dereferenced std::map object.
As a follow up, what if I had a std map inside a map and how to dereference that?
First you dereference myMaps, as shown above, then you access the inner map by key, exactly the same way you access any value by key, eg:
(*(test->myMaps))[1][2] = ...;
//(*test->myMaps)[1][2] = ...;
cout << (*(test->myMaps))[1][2];`
//cout << (*test->myMaps)[1][2];`
That being said, there is no good reason to use a pointer to a std::map at all. Use this instead:
class MyClass {
public:
std::map<int,int> myMaps;
};
int main() {
MyClass test;
std::map<int,int> testMap;
testMap[1] = 1;
test.myMaps = std::move(testMap);
// or, prior to C++11:
// test.myMaps.swap(testMap);
std::cout << test.myMaps[1] << std::endl;
}
class MyClass {
public:
std::map<int,std::map<int,int>> myMaps;
};
int main() {
MyClass test;
std::map<int,std::map<int,int>> testMap;
testMap[1][2] = 1;
test.myMaps = std::move(testMap);
// test.myMaps.swap(testMap);
std::cout << test.myMaps[1][2] << std::endl;
}
myMapsis a pointer? I can't think of any. This looks like something that Java programmers do when they start writing C++.(*test->myMaps)[1], exactly the same pattern you used above. BTW, make sure to run it withvalgrindand fix all the errors. You are leaking memory all over the place.newwithoutdeleteis a recipe for tears and, in a way, so are both of them combined. Either nestmyMapsdirectly intoMyClass, no need for explicit dynamic allocation, or, if you insist on dynamically allocating an STL container (which is an antipattern), please usestd::unique_ptr<std::map<int, int>>. Your future self will thank you andvalgrindwill praise you.std::map<int,int> myMaps;inMyClassand then, inmain(),std::map<int,int> testMap; testMap[1] = 1; test->myMaps = std::move(testMap);? Avoid raw pointers; you don’t need them in this case.