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
249 views
in Technique[技术] by (71.8m points)

c++ - 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.

question from:https://stackoverflow.com/questions/65642764/unordered-multimap-empty-returns-true-even-though-i-think-it-shouldve-returne

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

1 Answer

0 votes
by (71.8m points)
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)
//                                               ~^~

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

...