octnic
octnic

Reputation: 69

unordered_multimap.empty() returns true even though I think it should've returned false?

I'm new to using hash tables (AFAIK unordered_multimap is a hash table) and I'm trying to insert a struct in it using a function. My code:

Nod.h

#pragma once
#include <iostream>
#include <unordered_map>

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

    nod();
    void Citire(int n);
    void Init(std::unordered_multimap<int, nod*> hashTable);
};

Nod.cpp

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

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(std::unordered_multimap<int, nod*> hashTable)
{
    hashTable.insert({ pathManhattan + depth, this });
    hashTable.empty() ? std::cout << "da" : std::cout << "nu";
}

Consoleapplication.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()
{
    nod nodInitial; int n, t[1000];
    nodInitial.Init(theExplored);
    theExplored.empty() ? std::cout << "da" : std::cout << "nu";
    return 0;
}

This line from Init

hashTable.empty() ? std::cout << "da" : std::cout << "nu";

returns false

while this line from Consoleapplication.cpp returns true

theExplored.empty() ? std::cout << "da" : std::cout << "nu";

and I don't understand why.

Can anybody explain this to me?

I wanted to make a function inside the struct which would insert the specific variable of type nod into theExplored hash table, with an int as a key, but I don't know how to do it - I thought this might be the appropiate approach, but it seems like it isn't.

Upvotes: 0

Views: 38

Answers (1)

Lukas-T
Lukas-T

Reputation: 11350

void nod::Init(std::unordered_multimap<int, nod*> hashTable)

This takes it's parameter by value. That means it makes a copy and only modifies this local copy. The original map remains unchanged. Pass by reference instead:

void nod::Init(std::unordered_multimap<int, nod*> &hashTable)
//                                               ~^~

Upvotes: 2

Related Questions