gpt4 book ai didi

c++ - 在 std::map 中使用结构作为值时出现运行时错误?

转载 作者:行者123 更新时间:2023-11-28 05:08:53 25 4
gpt4 key购买 nike

我正在使用具有 int 值的映射 -> trie,trie 是结构。那么,当我在 map 中打印所有键值时,为什么会出现运行时错误?但是,如果我不打印任何东西,那么就没有错误(insert() 部分不会导致任何错误)。

struct trie{
node *root;
trie(){
root = new node();
}
void insert(int x){
node *cur = root;
for(int i = 31; i >= 0; i--){
int b = (x >> i) & 1;
if (cur->child[b] == NULL) cur->child[b] = new node();
cur = cur->child[b];
}
cur->isleaf = true;
}
int maxxor(int x){
node *cur = root;
int res = 0;
for(int i = 31; i >= 0; i--){
int b = (x >> i) & 1;
if (cur->child[b ^ 1] != NULL){
res |= (1ll << i);
cur = cur->child[b ^ 1];
}
else cur = cur->child[b];
}
return res;
}
int minxor(int x){
node *cur = root;
int res = 0;
for(int i = 31; i >= 0; i--){
int b = (x >> i) & 1;
if (cur->child[b] != NULL) cur = cur->child[b];
else{
res |= (1ll << i);
cur = cur->child[b ^ 1];
}
}
return res;
}
~trie(){
delete root;
}
};
map<int, trie> tr;
int32_t main(){
ios::sync_with_stdio(false);
tr[3].insert(1);// no error
for(auto x: tr) cout << x.first << ' '; //RUNTIME ERROR?
}

我已尝试调试和阅读各种问题/答案,但我仍然无法调试此代码。感谢任何帮助。

最佳答案

如果我可以说,你已经实现了一个“复杂”的树,使用链表。为了避免麻烦,您需要确保您的析构函数正确地执行它们的工作并且是连贯的,即销毁所有分配的内存并且不要“尝试”“销毁”未分配的空间或已经销毁的空间。

就是说,您的 trie 析构函数会破坏调用节点析构函数的根数据成员。并且节点析构函数破坏了两个不一定分配的 child 。这是您的段错误的根源。

要更正此问题,您应该只销毁分配的 child 。这是您的代码的简化版本

#include <bits/stdc++.h>
#define int int64_t
using namespace std;
struct node{
node* child[2];
bool isleaf;

node(){
child[0] = child[1] = NULL;
isleaf = false;
}

~node(){
}
};
struct trie{
node *root;
trie(){
cout << " in trie ctor" << endl;
root = new node();
}

void insert(int x){
cout << "in insert trie methode " << endl;

node *cur = root;

cur->child[0] = new node();
cur->child[1] = new node();

}

~trie(){
delete root->child[0]; // i'm sure it has been allocated
delete root->child[1]; // i'm sure it has been allocated
// delete root, would be like doing int *p; delete p;
}
};

map<int, trie> tr;
int32_t main(){

ios::sync_with_stdio(false);
tr[3].insert(1);
for(auto x: tr)
cout << x.first << endl << endl;
}

关于c++ - 在 std::map 中使用结构作为值时出现运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43962420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com