带有List插入的Segfault?

Hun*_*ves -1 c++ segmentation-fault

我觉得我可能会在这里忽略一些非常简单的东西,但是我已经制作了一些代码来测试列表中的插入/拼接,并且我对我制作的代码产生了一个段错误.有人可以告诉我在哪里/为什么?

#include <iostream>    
#include <vector>
#include <list>

using namespace std;
int main(){

vector <int> iVec;
list <int> iList;
vector<int>::iterator vIt;
list <int>::iterator lIt;

for(int i = 0; i < 10; i++){
    iVec.push_back(i*10);
    iList.push_back(i*10);
}//0, 10, 20, 30....90


//0 <-- current pos of iterator lIt

lIt++;  
lIt++; 

//0, 10, 20

iList.insert(lIt, 3);



//Vector output loop
for(vIt = iVec.begin(); vIt!= iVec.end(); vIt++){

}



cout << endl << endl <<"List Contents: " <<endl << endl;
//List output loop
for(lIt = iList.begin(); lIt != iList.end(); lIt++){
    cout << *lIt << endl;
}


return 0;
Run Code Online (Sandbox Code Playgroud)

}

Nim*_*Nim 5

lIt 尚未正确初始化 - 它是一个迭代器 - 但目前没有指向任何东西 - 你需要这样做:

lIt = iList.begin(); // initialize it to begin, now we can iterate!
Run Code Online (Sandbox Code Playgroud)

  • 在函数顶部声明变量是一个古老的C语言 - C++的最佳实践是仅在需要的地方创建变量,在尽可能窄的范围内创建变量,始终初始化,如果可能的话,创建const. (2认同)