我是使用哈希表的新手(AFAIK unordered_multimap 是一个哈希表),我正在尝试使用函数在其中插入一个结构。我的代码:
节点
#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);
};
节点文件#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)
这按值获取它的参数。这意味着它会创建一个拷贝并且只修改这个本地拷贝。原始 map 保持不变。改为通过引用传递:void nod::Init(std::unordered_multimap<int, nod*> &hashTable)
// ~^~
关于c++ - unordered_multimap.empty() 返回 true,即使我认为它应该返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65642764/