繁体   English   中英

在 cpp 中将堆栈作为结构元素处理

[英]Dealing with stack as struct element in cpp

我最近在做一个项目,偶然发现了以下情况

using namespace std;

//I have two structs, A basic struct as shown below
struct myAnotherStruct{
  int x;
  int y;
};

//A struct which embeds the stack of above struct type
struct myStruct{
  int a;
  float b;
  stack <myAnotherStruct> s;
};

//Somewhere else in the code, I created this
stack <myStruct> t;

//And performed following
struct myAnotherStruct var;
var.x = 10;
var.y = 20;

// But, when I performed the following operation, there was a core Dump!
t.s.push(var)

现在,我的问题如下,

  1. 为什么是核心转储? 每次添加新元素时不应该分配 memory 吗? 应该复制 var 并存储变量的 class (在我的情况下为 var)应该无关紧要!

  2. 做这样的事情是个好方法吗? 因为当我用谷歌搜索时,我总是得到“结构堆栈,结构向量”等,但不是其他方式(即堆栈结构)。

您正在创建一个myStruct堆栈,而不是myStruct实例。

//Somewhere else in the code, I created this
stack <myStruct> t;

您需要将其更改为:

myStruct t;

在原始代码中,编译器应该会生成一个错误,因为这里的stack没有成员s

// But, when I performed the following operation, there was a core Dump!
t.s.push(var)

这里的问题是您尝试访问堆栈的元素而不将项目推送到堆栈,如下所示:

myStruct m;  // Creates new myStruct object 
t.push(m);   // Adds object to stack

此外. 运算符不会自动获取堆栈中的顶部 object。 如果要将var添加到t中的成员变量s中,请考虑使用t.top().s.push(var); 获取堆栈的顶部元素,然后将汽车推入堆栈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM