3

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));
    }
};
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Machinarius
  • 3,637
  • 3
  • 30
  • 53

3 Answers3

5

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
        }
};
Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • Hmmm you made me realize that [As well as Mankarse], and adding a * in front of Raiz did the trick. what i dont seem to understand is that as far as i know, the de-reference (&) operator should of done it instead... why is this happening? – Machinarius Oct 15 '11 at 04:54
  • 1
    `&` is the "address-of" operator. `*` is the "dereference" operator. – Mankarse Oct 15 '11 at 04:56
  • 1
    `&` won't work in this case because it's still incompatible with `Nodo*` which is what `Raiz` is. – Mysticial Oct 15 '11 at 04:57
1

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;
        }
};
Mankarse
  • 39,818
  • 11
  • 97
  • 141
1

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)));
vishakvkt
  • 864
  • 6
  • 7