Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c++ - Using unordered_multimap with a struct data type

I need to define an unordered multimap which holds a key of type int and a value of type "nod".

Nod.h

#pragma once
#include <iostream>

struct nod {
    int stare[100], pathManhattan, depth;
    nod* nodParinte;
    char actiune;

    nod();
    void Citire(int n);
    void Init();
};

Nod.cpp

#include "Nod.h"
#include "ConsoleApplication1.cpp"

nod::nod()
{
    pathManhattan = 0;
    depth = 0;
    nodParinte = NULL;
}

void nod::Citire(int n)
{
    for (int i = 0; i < n*n; i++)
    {
        std::cin >> stare[i];
    }
}

void nod::Init()
{
    theExplored.insert({ pathManhattan + depth, this });
}

The problems is the Init function. I don't know how to make it work. ConsoleApplication1.cpp

#include <iostream>
#include <string>
#include <unordered_map>
#include "Nod.h"

std::unordered_multimap<int, nod> theExplored;
std::unordered_multimap<int, nod> theFrontier;

int main()
{
    return 0;
}

In my mind it should work, because every nod would have an init function which inserts the node it is used on in theExplored, but I think I might not understood unordered_multimap correctly.

Is my logic flawed? If so, how should I create a Hash table (AFAIK unordered_multimap is basically a hash table) with the key int and the value of type nod?

Also, how can I make a function in the struct so that node gets inserted into the hash table?

Thanks.

question from:https://stackoverflow.com/questions/65642340/using-unordered-multimap-with-a-struct-data-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you need to create a header file for the map definitions in your application source ConsoleApplication1.cpp. You can't just #include the source code as that will give you multiple definitions of your maps.

You can do this, create ConsoleApplication1.h:

#pragma once
#include <unordered_map>
#include "Nod.h"

extern std::unordered_multimap<int, nod> theExplored;
extern std::unordered_multimap<int, nod> theFrontier;

Notice the extern keyword. This means the code is just a declaration that the actual maps are defined elsewhere in the program (in an external file).

Of course your definitions are in ConsoleApplication1.cpp.

Now you can change your line #include "ConsoleApplication1.cpp" to #include "ConsoleApplication1.h" and that should solve your structural issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...