简体   繁体   English

无法逆向操作。 错误说它不能将 void 转换为字符串,但我的结果保存为字符串。 已显示代码以供参考

[英]not able to reverse operation. The error that says it cannot convert void to string but my result is saved as string. Have shown the code to refer

string result;
for(int i=st.size()-1;i>=0;i--){
 result+=st.top();
 cout<<st.top()<<endl;
 st.pop();}
 result+='\0';
 return reverse(result.begin(), result.end());

st is a stack of character. st 是一堆字符。 I want to output stack elements in reverse order我想以相反的顺序输出堆栈元素

The return value of std::reverse() is void , so you can't return it (except from a function that itself returns void ). std::reverse()的返回值是void ,因此您不能return它(除了本身返回void的函数)。

std:reverse() modifies the contents of the input range inline, so just return the std::string variable whose characters you are asking std::reverse() to modify, eg: std:reverse()内联修改输入范围的内容,因此只需return您要求std::reverse()修改其字符的std::string变量,例如:

string result;
while (!st.empty()){
    result += st.top();
    cout << st.top() << endl;
    st.pop();
}
reverse(result.begin(), result.end());
return result; // <-- here

Alternatively, you could just use string::insert() instead and not use std::reverse() at all, eg:或者,您可以只使用string::insert()而根本不使用std::reverse() ,例如:

string result;
result.reserve(st.size());
while (!st.empty()){
    result.insert(0, st.top());
    cout << st.top() << endl;
    st.pop();
}
return result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM