[英]Algorithm to convert std::stack to std::string in C++ STL
In below C++ program I'm deleting a previous character considering '#' as a backspace character.在下面的 C++ 程序中,我删除了将“#”视为退格字符的前一个字符。 I have used stack to build the string.
我已经使用堆栈来构建字符串。 Is there any C++ STL algorithm, which can help me to covert the std::stack to std::string.
是否有任何 C++ STL 算法可以帮助我将 std::stack 转换为 std::string。 Any alternative to the code with 'while' loop.
带有“while”循环的代码的任何替代方案。
string buildString(string s) {
stack<char> st;
for(auto a : s) {
if(a != '#') {
st.push(a);
}
else if(st.size()){
st.pop();
}
}
string result;
while(st.size()) {
result += st.top();
st.pop();
}
reverse(begin(result), end(result);
return result;
}
I'm deleting a previous character considering '#' as a backspace character.
我正在删除将“#”视为退格字符的前一个字符。 I have used stack to build the string.
我已经使用堆栈来构建字符串。
You could do this without additional space like std::stack
:您可以在没有额外空间的情况下执行此操作,例如
std::stack
:
std::string buildString(const std::string& s) {
std::string result;
for(auto a : s) {
if(a != '#') {
result += a;
}
else if(result.size()){
result.pop_back();
}
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.