我有以下代码尝试遍历向量。它以一个值和两个迭代器作为参数:start和end。它专门因while (start_iter != end_iter)
抛出EXC_BAD_ACCESS错误代码1而失败。
下面是爆炸的代码:
list<int>::iterator const
find_gt(
vector<list<int> >::iterator start_iter,
vector<list<int> >::iterator end_iter,
int value)
{
while (start_iter != end_iter)
{
if (start_iter->front() < value)
{
break;
}
++start_iter;
}
return start_iter->begin();
}
这是调用它的代码:
// Reads a file into the adjacency list
void readfile(string const filename, vector <list<int> > adjList)
{
std::ifstream file(filename);
if (!file.fail())
{
string line;
int i = 0;
int valueToInsert;
while (file >> valueToInsert)
{
auto it = find_gt(adjList.begin(), adjList.end(), valueToInsert);
adjList[i].insert(it, valueToInsert);
i++;
}
file.close();
}
else
{
cout << "Could not open file!\n";
throw std::runtime_error("Could not open file!");
}
}
int main()
{
// Vector of integer lists called adjList for adjacency list
vector <list<int> > adjList;
// Read the file contents into the adjacency list
readfile("input.txt", adjList);
return 0;
}
答案 0 :(得分:1)
在函数中,即使start_iter->begin()
等于start_iter
,也返回end_iter
。
那超出了内存的访问范围。