簡體   English   中英

帶指針的動態堆棧結構

[英]dynamic stack structures with pointers

我正在建立一個動態堆棧,該堆棧需要一個帶有數組指針的結構。

class studentstack
{

  private:
          struct StackNode
          {
                  int ID;
                  string Name;
                  string Address;
                  StackNode * next; // pointer to the next node
                  double * scores; // pointer to the arry of scores
          };

當在我的主文件中,im試圖用雙精度填充數組,然后將其傳遞給函數時,當我什么都不做時,似乎傳遞不對。 正確的做法是什么?

int main()
{
    studentstack s;

    string name;
    int id;
    string address;
    double score;




    for(int x =0; x<20; x++)
    {
        cout << "\nNew Student Name: ";
        cin >> name;

        cout << "\nID: ";
        cin >> id;

        cout << "\nAddress: ";
        cin >> address;

        double scoresArr[10];

        for(int z=0; z<10; z++)
        {
                cout << "\nStudent Score " << z+1 << ": ";
                cin >> score;
                scoresArr[z] = score;
        }

        s.push(name, id, address, scoresArr);

推:

void studentstack::push(string name, int id, string address, double scoresArr)
{
     StackNode *newStudent; // To point to the new Student

     newStudent = new StackNode;
     newStudent-> ID = id;
     newStudent-> Name = name;
     newStudent-> Address = address;
     newStudent-> scores = scoresArr;

     // If there are no nodes in the stack
     if (isEmpty())
     {
        top = newStudent;
        newStudent->next= NULL;
     }
     else // or add before top
     {
          newStudent->next = top;
          top = newStudent;
     }
}     

技術上的問題在於您尚未顯示的代碼(在我撰寫本文時),即push代碼。

但是,有一個簡單的解決方案將起作用,無論您的push如何。

即,使用std::vector而不是動態分配的原始數組。

或者,只需在每個節點中使用固定大小的原始數組。

為此, std::list會比DIY鏈接列表更好,但是大概整個練習的重點是要對鏈接列表結構有所了解。 對每個節點中的數組使用std::vector不會干擾該目標。 但是請記住,在現代C ++中,無論問題是什么,自己創建鏈接列表都很少是一個好的解決方案-而是使用標准庫容器類和/或第三方庫中的容器類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM