簡體   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