在<stack>初始化之前使用和自动迭代器,导致 SEG 错误

using <stack> and iterator with auto before initializing causing seg fault

本文关键字:迭代器 SEG 错误 导致 gt stack lt 初始化      更新时间:2023-10-16

我必须创建一个堆栈的迭代器,但是在将一些值压入堆栈之前,挣扎了一段时间后,我弄清楚了为什么下面的代码块导致segfault

#include <map>
#include <set>
#include <stack>
#include <utility>
#include <algorithm>
typedef std::stack<std::pair<short, std::set<short>>> stack_t;
int main()
{
    std::set<short> x = {0, 1, 2, 3};
    stack_t my_stack;
    auto iter = my_stack.top(); // error (segmentation fault)
    my_stack.push(std::make_pair(3, x));
    iter = my_stack.top();
    //...
    return 0;
}

是否有一种方法可以在初始化堆栈之前创建迭代器?

Top返回的不是迭代器,而是顶部元素,尽管堆栈是空的,这导致了错误。Stack不支持迭代器。它不是一个完全成熟的容器,而是一个容器适配器,它类似于底层容器的特殊类型定义,其默认值为deque。

请注意,依赖于数据结构的某些操作可能会使现有迭代器失效。你打算用你的迭代器做什么?

没有办法让迭代器进入堆栈——这违背了堆栈的目的,在堆栈中只能访问最上面的元素。当你试图

auto iter = my_stack.top();

不能得到迭代器,只能得到最上面的元素。在您的示例中,您尝试使用空堆栈,因此出现错误。