在<stack>初始化之前使用和自动迭代器,导致 SEG 错误
using <stack> and iterator with auto before initializing causing seg fault
我必须创建一个堆栈的迭代器,但是在将一些值压入堆栈之前,挣扎了一段时间后,我弄清楚了为什么下面的代码块导致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();
不能得到迭代器,只能得到最上面的元素。在您的示例中,您尝试使用空堆栈,因此出现错误。
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 为什么我在使用 istream 迭代器时会出现 seg 错误?
- 迭代器越来越多,并导致SEG故障
- 迭代器和向量的Seg错误
- 递归函数中迭代器的 Seg 错误
- 对set迭代器解引用会导致seg错误
- 在<stack>初始化之前使用和自动迭代器,导致 SEG 错误
- 常量迭代器的矢量构造函数内存分配,seg错误
- 迭代器,循环导致seg故障!为什么循环太多