开发者

Push String in Stack?

I am using 开发者_如何学JAVAC++ and i want to push strings in stack like push int in stacks.

For Example

3."stackoverflow"
2."is"
1."Best"
0."site"

at every index of stack I want to push a string. How can I do this?


Using STL, for example:

#include <stack>

std::stack<std::string> s;
s.push("A");
s.push("B");
s.push("C");
s.push("D");

Check the STL reference for more information.


Totally agree with Ton van den Heuvel, however you said

"at every index of stack I want to push a string"

What do you mean "at every index"? You should know that once the strings are in the stack, you can only access the top string and there is no access by index in a stack. If that's what you need, use std::vector instead.


I did it . I saw earlier how to convert string to character array and mixed it to what I am studying now ie. stacks.

stack <int> Name;
name="mohit";
for(char c:name)
 Name.push(c);
for(char c:name){
cout<<Name.top();
 Name.pop();}

And output was tihom It's function is simple. It converts string to character array and then pushes the string character by character. To pop out we use same loop and it pops out using LIFO principle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜