简体   繁体   English

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

[英]Dealing with stack as struct element in cpp

I was working on a project recently and stumbled upon following situation我最近在做一个项目,偶然发现了以下情况

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)

Now, My question are the following,现在,我的问题如下,

  1. Why core dump?为什么是核心转储? should'nt the memory be allocated every time I add a new element?每次添加新元素时不应该分配 memory 吗? the var should be copied and storage class of the variable (var in my case) should not matter!应该复制 var 并存储变量的 class (在我的情况下为 var)应该无关紧要!

  2. Is it a good approach to do something like this?做这样的事情是个好方法吗? Because when I googled, I always got "stack of structs, Vector of structs" etc but not the other way (Ie, Struct of stacks).因为当我用谷歌搜索时,我总是得到“结构堆栈,结构向量”等,但不是其他方式(即堆栈结构)。

You are creating a stack of myStruct and not a myStruct instance.您正在创建一个myStruct堆栈,而不是myStruct实例。

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

You need to change it to:您需要将其更改为:

myStruct t;

In the original code, the compiler should generate an error since stack has no member s here:在原始代码中,编译器应该会生成一个错误,因为这里的stack没有成员s

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

The problem here is that you attempt to access an element of the stack without pushing an item to the stack like so:这里的问题是您尝试访问堆栈的元素而不将项目推送到堆栈,如下所示:

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

Furthermore the .此外. operator does not automatically get the top object in the stack.运算符不会自动获取堆栈中的顶部 object。 If you want to add var to the member variable s in t , consider using t.top().s.push(var);如果要将var添加到t中的成员变量s中,请考虑使用t.top().s.push(var); to get the top element of the stack and then push car to the stack.获取堆栈的顶部元素,然后将汽车推入堆栈。

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

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