FriedRice
FriedRice

Reputation: 29

How to dereference an std::map member pointer inside a class?

I'm currently learning C++ and ran across this that has me stumped. I have this class:

class MyClass {
  public:      
    std::map<int,int> *myMaps;
}

How do I dereference myMaps? This does not work.

int main() {
  MyClass *test = new MyClass();
  std::map<int,int> *testMap = new std::map<int,int>();
  (*testMap)[1] = 1;

  test->myMaps = testMap;
  std::cout << *test->myMaps[1] << std::endl;

As a follow up, what if I had a std map inside a map and how to dereference that?

class MyClass {
  public:      
    std::map<int,std::maps<int,int>> *myMaps;
}

Upvotes: 0

Views: 625

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596307

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

Upvotes: 1

Related Questions