【问题标题】:Dealing with stack as struct element in cpp在 cpp 中将堆栈作为结构元素处理
【发布时间】:2020-09-11 07:34:24
【问题描述】:

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

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. 为什么是核心转储?每次添加新元素时不应该分配内存吗? var 应该被复制并且变量的存储类(在我的例子中是 var)应该无关紧要!

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

【问题讨论】:

标签: c++ struct stl stack


【解决方案1】:

您正在创建一个 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)

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      相关资源
      最近更新 更多