执行错误访问 遍历向量

EXEC BAD ACCESS Iterating through vector

本文关键字:向量 遍历 访问 错误 执行      更新时间:2023-10-16

我有以下代码试图遍历一个向量。它接受一个值和两个迭代器作为参数:开始和结束。它特别失败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;
}

在你的函数中,你返回start_iter->begin(),即使start_iter等于end_iter

这是内存的越界访问。