为C++中的无序映射获取给定输入键的错误值
Obtaining wrong Value of a given input Key for an unordered map in C++
我正在尝试使用自定义构建的哈希函数将对象存储在无序映射中,下面是代码,
#include <iostream>
#include <unordered_map>
#include <string>
//Class that I want to store in unordered map
class Tree{
public:
int val;
std::pair<int,int> location;
Tree(int val,std::pair<int,int> location){
this->location = location;
this->val = val;}
};
//I guess this operator is internally used by the unordered map to compare the Values in the maps.
//This function returns True only when the val of both the nodes are equal.
bool operator ==(const Tree& node1, const Tree& node2){
return node1.val == node2.val;}
//Custom build Hash Function for assigning Keys to the Values.
class HashFunction{
public:
size_t operator()(const Tree& node) const{
std::hash<int> Hash;
return Hash(node.val);
}
};
//Created a class dictionary using the std::unordered_map to store the objects.
class dictionary{
public:
std::unordered_map<Tree,Tree*,HashFunction> dict;
void append(Tree node){
this->dict[node] = &node;}
Tree* get(Tree node){
return this->dict[node];}
};
int main(){
Tree obj1(1,std::make_pair(1,6));
Tree obj2(2,std::make_pair(2,5));
Tree obj(2,std::make_pair(3,4));
dictionary dict;
dict.append(obj1);
dict.append(obj2);
std::cout<<"#################"<<std::endl;
std::cout<<dict.get(obj)->location.first<<std::endl;
}
获得的结果是">3"(如obj.val(,而不是">2(如obj2.val("。
我在主函数中创建了三个对象,即Tree类obj1、obj2和obj。obj1和obj2存储在字典中,obj用于检查字典中的匹配对象。由于Hash函数使用对象的val来创建Key,因此obj2和obj都将具有相同的Key,但当我试图以obj作为输入访问字典时,字典应该返回obj2,而我得到的是不在字典中的obj,我不明白为什么会发生这种情况。如有任何建议,我们将不胜感激。提前感谢:(
在dictionary::append
中,插入一个指向局部变量(node
(的指针作为值:
this->dict[node] = &node;
一旦函数结束,此指针将不再有效。
稍后尝试取消引用该指针会导致未定义的行为。这种未定义的行为(在您的情况下(通过访问错误的对象(特别是dictionary::get
函数的参数(来表现出来。情况可能会更糟。
要修复它,您可以简单地将函数更改为:
void append(Tree& node){
this->dict[node] = &node;}
您仍然需要依赖main
中的对象来保持现有,但至少它应该做您想要做的事情。
相关文章:
- 堆栈中大小变量输入错误 (C++)
- 如果用户没有输入任何内容或输入错误,如何重新输入用户的输入?
- 如何从标准输入中检测格式化输入错误?
- 如何在没有打印语句的情况下报告用户输入错误
- 用户输入错误
- 按下Enter时如何输入错误消息,但没有给出任何答案
- 在我的IF-ELSE循环中输入错误
- C++ 输入错误
- C++ 函数输入错误
- 使用ifstreamwhile循环,如何显示输入错误并在下一行继续
- switch 语句中的输入错误 如何循环回第一种情况?C++
- 在 switch 语句中输入字符以进行C++时用户输入错误
- 如果我输入错误的 dos 命令,shellexecute 会给出正确的结果
- C++输入错误的数组
- scanf和多个输入错误
- C++输入浮点而不是整数时的输入错误
- 使用字符串流和if-else语句时发生字符串输入错误
- 当用户输入错误输入时,一次清除 cin 中的整行而不是一个字符
- setw() 在包含 UTF-8 多字节字符/码位的字符串上输入错误的输出
- c++中的getline输入错误