将结构体链表添加到数组中会产生错误
Adding a linked list of structs to an array produces an error
这是我第一次在这个网站上提问,所以如果我违反了任何礼仪,请告诉我。
我对链表非常陌生,并认为使用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
相同的功能,除了:
-
list
。 -
list
是一个双链表,它使用的内存是vector
的4倍。 -
list
即使以顺序方式访问也比vector慢。这是由于vector更容易缓存,因为它是本地化的。 -
list
通常在其他方面也比vector
慢。
[]
操作符不能像vector
那样随机访问list的唯一"优点"是插入新元素不会使迭代器失效。但是无论如何,向量索引都比迭代器更可靠,所以除非绝对需要,否则不要使用迭代器。
和push_front
以相反的顺序构建列表,通常应该使用push_back
。
相关文章:
- "错误:数组下标的无效类型'float [10001][float]'是什么意思?
- 错误:数组下标的类型"const bool[int]"无效
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 使用GCC 4.8构建错误:数组用作初始化器
- 如何修复问题中的"teminated due to timeout"错误 数组操作 |黑客兰克?
- | 9 |错误:非静态数据成员'matrix :: row'| 9 |错误:数组绑定不是在']']'令牌|之前的整数常数
- 错误:数组的总大小不得超过0x7fffffff字节
- 错误:无法将参数“1”的“double*”转换为“double”,错误:数组下标的类型“double[double]”无
- 返回并强制转换数组指针(错误:数组下标的类型..无效)
- 返回c++中的字符错误数组
- VC++错误:数组实例化的大小来自模板化的静态常量
- c++mex错误:数组下标的类型“double[mwSize]”无效
- 错误数组用作初始值设定项,我不知道错误
- 编译错误 - 数组下标'char[int]'的类型无效
- 向量在我的类中.错误:数组new [-fpermissive]中的圆括号初始化项
- 错误:数组下标的类型无效
- 错误:数组new中的size必须是整型[-fpermissive]
- 错误:数组下标的“Pixel*[__complex__ int]”类型无效
- c++错误数组显示
- C++:错误:数组下标的类型“size_t{aka long unsigned int}[size_t{aka long