Reputation: 77
#include <iostream>
using namespace std;
#include <string>
#include <map>
typedef struct node{
char a;
map<char , node*> b;
}node;
node a[26] ;
void add(string s){
node *prev = &(a[s[0]-'a']);
int i = 0;
int len = s.length();
for(i = 1; i < len; ++i){
map<char,node*>::iterator it = ((*prev).b).find(s[i]);
if(it != ((*prev).b).end()){
prev = it->second;
}
else{
cout << (*prev).a << endl;
node pt;
pt.a = s[i];
((*prev).b)[s[i]] = &pt;
prev = &pt;
}
}
}
int main(){
string s = "helloworld";
string t = "htllothis";
int i = 0 ;
for(i = 0;i < 26;++i){
a[i].a = 'a'+i;
}
add(s);
add(t);
return 0;
}
I am trying to implement tire datastructure using map and char but cout<< (*prev).a
is printing some other chars. What is the mistake I have done?
Upvotes: 0
Views: 75
Reputation: 44268
First of all (*prev).b
is equivalent to prev->b
, I do not understand why you use ->
for iterator but not for this pointer, it is difficult to read your code.
Main problem that you insert pointer to a local object into map:
cout << (*prev).a << endl;
node pt;
pt.a = s[i];
((*prev).b)[s[i]] = &pt;
prev = &pt;
After leaving this block that pointer becomes invalid and you get random errors. You either should create node by operator new and better have smart pointer in your map, or keep node by value.
Upvotes: 4
Reputation: 1974
(...)
node pt;
pt.a = s[i];
((*prev).b)[s[i]] = &pt;
prev = &pt;
(...)
In your add
function you're creating a local node
and passing its address into an entry of the map and then make it the prev
node. Once the variable is out of scope it is deleted and your prev
node points to an invalid address. So next time you print prev
anything could happen as it is Undefined Behaviour.
Upvotes: 0