[英]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
)。 使用vector
( std::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.