unordered_multimap.empty() 返回 true,即使我认为它应该返回 false?

时间:2021-01-09 12:45:00

标签: c++ c++11

我是使用哈希表的新手(AFAIK unordered_multimap 是一个哈希表),我正在尝试使用函数在其中插入一个结构。我的代码:

点头.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";
}

控制台应用程序.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;
}

来自Init的这一行

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

返回错误

而 Consoleapplication.cpp 中的这一行返回 true

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

我不明白为什么。

谁能给我解释一下?

我想在结构中创建一个函数,它将类型 nod 的特定变量插入到探索的哈希表中,以 int 作为键,但我不知道该怎么做 - 我认为这可能是合适的方法,但似乎不是。

1 个答案:

答案 0 :(得分:2)

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

这会按值获取它的参数。这意味着它会创建一个副本并且只修改这个本地副本。原始地图保持不变。改为通过引用传递:

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