Reputation: 1
I want to assign the values in stack to the string without using the method used below. Are there any possible ways/method to perform this in C++? *Assuming there are character values present in the stack.
stack<char> K;
string ans="";
while(!K.empty()){
ans+=K.top();
K.pop();
}
reverse(ans.begin(),ans.end());
return ans;
Thank you in advance.
Upvotes: 0
Views: 2106
Reputation: 1248
One way of doing it in linear time without reversing at the end:
string str;
str.resize(K.size());
size_t back = str.size() - 1;
while(!K.empty()){
str[back--] = K.top();
k.pop();
}
Upvotes: 1
Reputation: 10604
With C++11 and later, you could do something like this:
stack<char> K;
string ans;
ans.resize(K.size());
auto it = ans.rbegin(); // use reverse iteration over the string
while (!K.empty()) {
*it = K.top();
K.pop();
++it;
}
A more efficient solution would be to not use the stack in the first place. Or, at least, you could use your own stack class that allows to export its contents in forward order:
class my_char_stack :
public std::stack<char>
{
public:
void export_string(std::string& str)
{
// std::stack has protected member c, which is the container with
// its elements stored in forward order
str.append(c.begin(), c.end());
}
};
my_char_stack K;
string ans;
K.export_string(ans);
Upvotes: 1