I have a program takes inputs from 2 files in c++. Then identify Is the second input file is topological sort? but somehow if i use the list.empty() in a while loop statement, it gives me a segmentation fault, but the for loop doesnt give me any error; however, the for loop only loop once, since i might need to go throught twice.
#include <list>
#include <iostream>
#include <vector>
using namespace std ;
list<unsigned> output;
list<unsigned> &
testSort ( istream & idata , istream & sdata )
{
unsigned n,x1,x2;
vector< list<unsigned> > successor(n);
vector<unsigned> count(n,0);
vector<bool> marks(n,false);
idata >>n;
for(int i=0;i<n;i++) {
idata>>x1>>x2;
count[x2]++;
successor[x1].push_back(x2);
if(idata.eof()) break;
}
for(int i=0;i<n;i++) {
sdata>>x1;
if(count[x1]==0) {
marks[x1]=true;
//for(int j=0;j<successor[x1].size();++j) {
while(!successor[x1].empty()) {
count[successor[x1].front()]--;
successor[x1].pop_front();
}
}
else {
for(int i=0;i<n;i++)
{
if(marks[i]==false)
output.push_back(i);
}
break;
}
}
return output;
}
This is a clear error — you’re using
nto specify the size ofsuccessor, butnhasn’t been initialized yet, so it contains garbage (and the same is true withcountandmarkssince you’ve specified their size asnas well). In other words, at this point, we have no clue about the size ofsuccessor.You have a couple of choices. You could move your
idata >> n; before you definesuccessor,count, andmarks, or you could define them without a size, and then useresizeto specify their size after you readnfromidata.I’ll leave off my usual rant about
std::listbeyond pointing out that I rarely find it an optimal choice.