C++ 获取C+中无序映射的给定输入键的错误值+;

C++ 获取C+中无序映射的给定输入键的错误值+;,c++,class,dictionary,pointers,unordered-map,C++,Class,Dictionary,Pointers,Unordered Map,我试图使用自定义构建哈希函数将对象存储在无序映射中,下面是代码 #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,

我试图使用自定义构建哈希函数将对象存储在无序映射中,下面是代码

#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;    

}
#包括
#包括
#包括
//类,我要将其存储在无序映射中
类树{
公众:
int-val;
std::配对位置;
树(int-val,std::pair-location){
这个->位置=位置;
此->val=val;}
};
//我猜这个操作符是无序映射内部用来比较映射中的值的。
//仅当两个节点的val相等时,此函数才返回True。
布尔运算符==(常数树和节点1、常数树和节点2){
返回node1.val==node2.val;}
//自定义生成哈希函数,用于为值分配键。
类哈希函数{
公众:
size\u t运算符()(常量树和节点)常量{
std::散列;
返回散列(node.val);
}
};
//使用std::unordered_映射创建一个类字典来存储对象。
类词典{
公众:
std::无序地图目录;
无效附加(树节点){
此->dict[node]=&node;}
树*get(树节点){
返回此->dict[node];}
};
int main(){
树obj1(1,std::make_对(1,6));
树obj2(2,std::make_-pair(2,5));
树obj(2,std::make_对(3,4));
词典词典;
dict.append(obj1);
dict.append(obj2);

std::cout在
字典::append
中,插入指向局部变量(
节点
)的指针作为值:

一旦函数结束,此指针将不再有效

尝试在稍后点取消引用该指针会导致。这种未定义的行为(在您的情况下)通过访问错误的对象(特别是
dictionary::get
函数的参数)而表现出来。情况可能更糟

要解决此问题,只需将函数更改为:

void append(Tree& node){
    this->dict[node] = &node;}

您仍然需要依赖
main
中的对象来保持现有状态,但至少它应该做您看起来想要做的事情。

this->dict[node]=&node;
将导致未定义的行为,因为无序的_映射将存储指向局部变量的指针,这些变量在函数离开后将过期。您的意图是什么?您不必要地复制了大量的
对象,这(至少部分)导致了此问题。请尝试在适当的时候使用。
void append(Tree& node){
    this->dict[node] = &node;}