标签: stdstack

std::stack 是连续的吗?

我想找到堆栈中的最大元素,并考虑使用std::max_element.

然后我才知道std::stack没有begin()end()功能。在网上冲浪后,我看到了一个黑客:

stack<int> s({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto end = &s.top() + 1;     // instead of std::end
auto begin = end - s.size(); // instead of std::begin
cout << "Max = " << *max_element(begin, end);
Run Code Online (Sandbox Code Playgroud)

好像可以用,网上可以看看

但是当我提交我的代码时,它在一些测试用例中失败了。std::stack真的是连续的吗?

c++ stdstack

4
推荐指数
1
解决办法
257
查看次数

不同容器上的 std::stack 实现有什么实际区别?

当实施一个 std::stack

有几个选项,例如:

   // stack with default underlying deque
   std::stack< int > intDequeStack;   

   // stack with underlying vector
   std::stack< int, std::vector< int > > intVectorStack;

   // stack with underlying list
   std::stack< int, std::list< int > > intListStack;
Run Code Online (Sandbox Code Playgroud)

std::stack 当我从中得到的只是相同的操作“push、pop 和 top”时,我从在不同的容器上定义有什么优点和缺点?

换句话说:一堆双端队列和一堆向量和一堆列表之间有什么区别,为什么我要选择双端队列以外的任何东西?

c++ containers stl stdstack

3
推荐指数
1
解决办法
140
查看次数

不了解 C++ stack&lt;char*&gt; 行为

我被困了两个小时试图了解这个简单的 C++ 测试程序中发生了什么,但仍然没有明白。它应该只接收三个字符串作为输入,将它们插入一个堆栈,最后打印该堆栈的所有元素。

#include <iostream>
#include <stack>
#include <cstring>

using namespace std;

int main(){
    
    stack<char*> stk;
    
    int stringLength;
    
    for (int i=0; i<3; i++){
        char new_element[200];
        scanf("%s", new_element);
        stringLength = strlen(new_element);
        stk.push(new_element);
    }
    
    cout << "Stack content: ";
    while(!stk.empty()){
        cout << stk.top() << " ";
        stk.pop();
    }
    cout << endl;

}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,最终输出的是同一个元素(最后添加的)打印了 3 次,这对我来说毫无意义。

例如,如果输入是:

John
Mary
Rick
Run Code Online (Sandbox Code Playgroud)

那么当前的输出是

Rick
Rick
Rick
Run Code Online (Sandbox Code Playgroud)

谁能帮我理解和解决这个问题?

c++ std stdstack

1
推荐指数
1
解决办法
60
查看次数

标签 统计

c++ ×3

stdstack ×3

containers ×1

std ×1

stl ×1