将结构体链表添加到数组中会产生错误

Adding a linked list of structs to an array produces an error

本文关键字:错误 数组 结构体 链表 添加      更新时间:2023-10-16

这是我第一次在这个网站上提问,所以如果我违反了任何礼仪,请告诉我。

我对链表非常陌生,并认为使用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]。和你的调试器谈谈,它会证明我是对的。

如果ty != "NEW",则pid仍然等于-1。

processList (pid) .push_front (newEntry);

将崩溃,因为下标越界(-1)

尽管链表有多棒,但不要使用list(或没有" using namespace std "位的std::list)。使用vector (std::vector).

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

    []操作符不能像vector 那样随机访问
  • list
  • list是一个双链表,它使用的内存是vector的4倍。
  • list即使以顺序方式访问也比vector慢。这是由于vector更容易缓存,因为它是本地化的。
  • list通常在其他方面也比vector慢。

list的唯一"优点"是插入新元素不会使迭代器失效。但是无论如何,向量索引都比迭代器更可靠,所以除非绝对需要,否则不要使用迭代器。

push_front以相反的顺序构建列表,通常应该使用push_back