微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我是使用哈希表的新手(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 作为键,但我不知道该怎么做 - 我认为这可能是合适的方法,但似乎不是。

解决方法

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。