AndreaM16 AndreaM16 - 4 months ago 24
C++ Question

Correctly Initialize Map of Pointers - map<p*, p*>

I'm pretty new to C++ and even looking to related Q/A on SO I didn't find a proper answer to my issue.

I'm really struggling trying to instantiate a new map of pointers

map<p1*, p2*>

So far, I tried:

std::map<myType*, myType*> mapOfVertices = new std::map<myType, myType>;


std::map<myType*, myType*> mapOfVertices = new std::map<myType*, myType*>;

But I'm always getting:

error: conversion from ‘std::map*’ to non-scalar type ‘std::map’ requested
std::map mapOfVertices = new std::map;

I'm very confused since I already managed to initialize successfully other objects like:

myType* myObj = new myType;

I'm sorry if my question is a bit trivial. Thanks in advance.


You don't need to allocate the map object itself on the heap, you can just create it on the stack.

std::map<myType*, myType*> mapOfVertices;

That code sufficiently creates the map. If, for whatever reason, you did want a pointer to the map (which involves allocating it on the heap), you'd need to change the declaration to

std::map<myType*, myType*> * mapOfVertices = new std::map<myType*, myType*>;

(Note the extra star between the type and the variable name)

Based on the code you've provided, and by your own admission, you are indeed a novice to C++, as most experienced C++ programmers know to only work with raw pointers when absolutely necessary, and your use case definitely does not represent such a case. I strongly, strongly recommend you pick up a book. There's a great listing here with suggestions.