[英]How can I pass a C++ String through reference?
I am writing a huffcode program, and I'm going through every branch of the tree to to find the code for each alphabet.我正在编写一个 huffcode 程序,并且我正在遍历树的每个分支以找到每个字母表的代码。 How can I pass the string to insert it?如何传递字符串以插入它? Also, Im getting errors from the way I declared my string vector, but Ive used vectors all over my code.另外,我在声明字符串向量的方式中遇到了错误,但我在整个代码中都使用了向量。 Is there something I am doing wrong?有什么我做错了吗?
void treeTraverser(Node* root, char string, vector<char> const &alpha,
vector<string> const &huffcode){
if(root->left!=NULL){
string=string+'0';
treeTraverser(root->left, string, alpha, huffcode);
}
if(root->right!=NULL){
string=string+'1';
treeTraverser(root->right, string, alpha, huffcode);
}
alpha.push_back(root->key);
huffcode.push_back(string);
}
Change char
to string&
in your string
parameter (and consider renaming it, too).在您的string
参数中将char
更改为string&
(并考虑重命名它)。
Also, get rid of the const
on the huffcode
parameter.另外,去掉huffcode
参数上的const
。 You can't push_back()
into a const vector
object.您不能将push_back()
放入const vector
object。
void treeTraverser(Node* root, string &str, vector<char> const &alpha, vector<string> &huffcode)
{
if (root->left){
str += '0';
treeTraverser(root->left, str, alpha, huffcode);
}
if (root->right){
str += '1';
treeTraverser(root->right, str, alpha, huffcode);
}
alpha.push_back(root->key);
huffcode.push_back(str);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.