unordered_multimap.empty()返回true与预期不符的问题排查及结构体插入哈希表实现咨询
正确的实现方法
下面给你两种常用的修正方案,选一种就行:
方案1:传递哈希表的引用(推荐)
引用传递会让函数直接操作原哈希表,而不是副本。
- 修改
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"; }
这样修改后,当你在主函数调用nodInitial.Init(theExplored)时,insert操作会直接作用在全局的theExplored上,主函数里再判断它是否为空就会得到正确的结果了。
方案2:传递哈希表的指针(可选)
如果你更习惯用指针的方式,也可以这么实现:
- 修改
Nod.h的函数声明:
void Init(std::unordered_multimap<int, nod*>* hashTable);
- 修改
Nod.cpp的函数定义:
void nod::Init(std::unordered_multimap<int, nod*>* hashTable) { // 先判断指针是否为空,避免空指针访问崩溃 if (hashTable == nullptr) { std::cout << "哈希表指针为空!" << std::endl; return; } hashTable->insert({ pathManhattan + depth, this }); hashTable->empty() ? std::cout << "da" : std::cout << "nu"; }
- 主函数调用时要传递地址:
nodInitial.Init(&theExplored);
额外的小建议
- 你的
stare是固定大小的数组(100),如果n是用户输入的可变值,很容易出现数组越界的问题,建议换成std::vector<int>,它可以动态调整大小,更安全灵活。 - 因为你在哈希表里存储的是
nod*指针,记得在程序结束前手动释放这些指针指向的内存,避免内存泄漏。
内容的提问来源于stack exchange,提问作者octnic
相关产品推荐
相关产品推荐

