簡體   English   中英

將結構的鏈接列表添加到數組會產生錯誤

[英]Adding a linked list of structs to an array produces an error

這是我第一次在此網站上提問,因此,如果我違反任何禮節,請告訴我。

我對鏈表真的很陌生,並認為使用list數據類型實現list非常簡單,但是似乎我正在嘗試對它們做一些奇怪的事情。

我創建了一個名為“ eventList”的list ,我要在其中放入一系列名為“ entry”的struct ,然后希望將多個“ eventList”放入一個名為“ processList”的數組中。

我的問題是一點點代碼

processList[pid].push_front(newEntry);

似乎給我一個錯誤。 我的工作明顯有問題嗎?

這是代碼:

#include <iostream>
#include <fstream>
#include <list>
#include <string>
#include <array>

using namespace std;

struct entry {
    int eTime;
    string eType;
    int pid;
};

int main(){
ifstream infile;
string comm;
int num;

entry newEntry;
list<entry> eventList;
array<list<entry>, 1024> processList;


infile.open("input00.txt");

if(infile.is_open()){
    while(!infile.eof()){
        int pid = -1;
        string eTy;
        int eTi;
        infile >> eTy;
        infile >> eTi;

        if(eTy == "NEW"){
            pid++;
            cout << "DB: Process " << pid << endl;
        }
        else{
            newEntry.pid = pid;
            newEntry.eType = eTy;
            cout << "Type: " << newEntry.eType << " | ";
            newEntry.eTime = eTi;
            cout << "Time: " << newEntry.eTime << endl;
            processList[pid].push_front(newEntry);
            //processList[pid] = eventList;  <- realized that that wouldn't work fairly quickly
        }
    }
}

else {
    cout << "Sorry, that file doesn't work. :[" <<endl;
}

cout << "Original Order:" << endl;

list<entry>::iterator p = eventList.begin();

while(p != eventList.end()){
    cout << p->eType << " For " << p->eTime << "\n";    //This comes from http://www.cplusplus.com/forum/beginner/3396/
    p++;
}

//cout << "Ordered By Time:\n";

//eventList.sort(); <- commented out, because I can't get it to work. :[

system ("PAUSE");
return 0;
}

我非常喜歡此資源可用,並且希望我能遵循以這種方式得出的任何答案的邏輯。 抱歉,我們很高興!

您正在while循環中初始化pid。 因此,無論您做什么,都將引用array [-1]。 與您交談的是調試器,這將證明我是正確的。

如果eTy!=“ NEW”,則pid保持等於-1。

所以,

PROCESSLIST [PID] .push_front(newEntry);

將因為下標超出范圍而崩潰(-1)

盡管鏈接列表非常棒,但不要使用list (或不帶“ using namespace std ”位的std::list )。 使用vectorstd::vector )。

std::list提供與std::vector相同的功能,除了:

  • 不能使用[]運算符(如vector隨機訪問list
  • list是一個雙鏈表,它使用約4倍的內存作為小型結構的vector
  • 與矢量相比,即使以順序方式訪問list也較慢。 這是由於向量已經本地化,因此更易於緩存。
  • 在所有其他方面, list通常也比vector要慢。

列表中唯一插入新元素的“優點”不會使迭代器無效。 但是矢量索引比迭代器更可靠,因此除非絕對必要,否則永遠不要使用迭代器。

並且push_front以相反的順序構建列表,通常應使用push_back

暫無
暫無

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

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