我遇到上述错误,如果有人有任何想法请帮助我。
我在void traverse
函数中收到此错误,其中我使用insert
函数插入地图。
struct node {
int weight;
unsigned char value;
const node *child0;
const node *child1;
map<unsigned char, string> huffmanTable;
node( unsigned char c = 0, int i = -1 ) {
value = c;
weight = i;
child0 = 0;
child1 = 0;
}
node( const node* c0, const node *c1 ) {
value = 0;
weight = c0->weight + c1->weight;
child0 = c0;
child1 = c1;
}
bool operator<( const node &a ) const {
return weight >a.weight;
}
void traverse(ostream& o,string code="") const {
if ( child0 ) {
child0->traverse(o, code + '0' );
child1->traverse(o, code + '1' );
} else {
o<<value<<"\t";
cout <<" " <<value <<" ";
o<<weight<<"\t";
cout <<weight;
o<<code<<endl;
cout <<" " <<code <<endl;
huffmanTable.insert(pair<unsigned char, std::string>(value,code));
}
}
};
答案 0 :(得分:3)
您正尝试从const函数添加到地图 huffmanTable 。 const成员函数不允许修改 this 对象。你的选择是
您可以将地图设为可变
mutable map huffmanTable;
或
从遍历函数中删除const
void traverse(ostream&amp; o,string code =“”){