【问题标题】:unordered_multimap.empty() returns true even though I think it should've returned false?unordered_multimap.empty() 返回真,即使我认为它应该返回假?
【发布时间】:2021-01-09 12:45:00
【问题描述】:

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

【问题讨论】:

  • 你没有通过引用探索。

标签: c++ c++11


【解决方案1】:
void nod::Init(std::unordered_multimap<int, nod*> hashTable)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-06
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多