【发布时间】:2015-07-24 13:08:14
【问题描述】:
#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;
}
我正在尝试使用 map 和 char 实现轮胎数据结构,但 cout<< (*prev).a 正在打印其他一些字符。我犯了什么错误?
【问题讨论】:
-
预期输出是什么,你得到什么输出?
-
它必须打印“helloworl”和“tllothis”的字符,每个字符都带有换行符,但它正在打印一些垃圾值。
-
typedef struct node { ... } node;非常喜欢 C。在 C++ 中,您可以简单地使用struct node { ... };,因为node可以在没有typedef的情况下使用。 -
@crashmstr
typedef struct废话让我发疯,多么糟糕的解决方案。
标签: c++ pointers dictionary