将字符串压入堆栈?

发布于 2024-09-26 19:25:08 字数 171 浏览 0 评论 0原文

我正在使用 C++,我想将字符串推送到堆栈中,就像推送 int 一样。

例如,

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

在堆栈的每个索引处,我想推送一个字符串。我该怎么做?

I am using C++ 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情深缘浅 2024-10-03 19:25:08

例如,使用 STL:

#include <stack>

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

查看 STL 参考以获取更多信息。

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.

傲娇萝莉攻 2024-10-03 19:25:08

完全同意 Ton van den Heuvel,不管你怎么说

“在我想要的堆栈的每个索引处
推一根绳子”

“在每个索引处”是什么意思?您应该知道,一旦字符串进入堆栈,您只能访问顶部字符串,并且无法通过堆栈中的索引进行访问。如果这就是您需要的,使用 std::vector 代替。

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.

酸甜透明夹心 2024-10-03 19:25:08

我做到了 。我之前看到了如何将字符串转换为字符数组,并将其与我现在正在学习的内容混合在一起。堆栈。

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

输出为 tihom

它的功能很简单。它将字符串转换为字符数组,然后逐个字符地推送字符串。为了弹出,我们使用相同的循环,并且它使用 LIFO 原理弹出。

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 <char> 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文