问题
I'm having an issue with inserting an entry into a Map.
#include <stdio.h>
#include <vector>
#include <stack>
#include <map>
using namespace std;
class Nodo
{
public:
vector<Nodo> Relaciones;
int Valor;
bool Visitado;
Nodo(int V)
{
Valor = V;
Visitado = false;
}
};
class Grafo
{
public:
Nodo *Raiz;
map<int, Nodo> Nodos;
Grafo(int V)
{
Raiz = new Nodo(V);
//Getting http://msdn.microsoft.com/en-us/library/s5b150wd(v=VS.100).aspx here
Nodos.insert(pair<int, Nodo>(V, Raiz));
}
};
回答1:
You have a type mismatch. You're passing a Nodo*
into the pair
constructor while it expects a Nodo
object.
You declare:
Nodo *Raiz;
and then you try to call:
pair<int, Nodo>(V, Raiz)
which expects an int
and a Nodo
. But you passed it int
and Nodo*
.
What you probably want is this:
class Grafo
{
public:
Nodo *Raiz;
map<int, Nodo*> Nodos; // change to pointer
Grafo(int V)
{
Raiz = new Nodo(V);
//Getting http://msdn.microsoft.com/en-us/library/s5b150wd(v=VS.100).aspx here
Nodos.insert(pair<int, Nodo*>(V, Raiz)); // change to pointer
}
};
回答2:
The problem is that Rais
is a pointer to Nodo
, but you are trying to insert it into a map from int
to Nodo
(not a map from int
to Nodo*
).
Try:
class Grafo
{
public:
Nodo *Raiz;
map<int, Nodo> Nodos;
Grafo(int V)
{
Raiz = &*Nodos.insert(pair<int, Nodo>(V, Nodo(V))).first;
}
};
回答3:
As previously mentioned, 'new' returns a pointer to the object. In order to obtain the object itself, you would need to dereference it by using the '*' operator. That is why the map fails to work.
Additionally if you want to insert values into a map which I personally believe looks clearer is by doing
typedef map<int, Nodo> MyMap;
MyMap myawesomemap;
int V = 5;
Nodo* Raiz = new Raiz(5);
myawesomemap.insert(MyMap::value_type(V, (*Raiz)));
来源:https://stackoverflow.com/questions/7775803/debugging-map-insertion