gpt4 book ai didi

c++ - EXEC BAD ACCESS 遍历 vector

转载 作者:行者123 更新时间:2023-11-28 04:32:30 24 4
gpt4 key购买 nike

我有以下代码试图遍历一个 vector 。它以一个值和两个迭代器作为参数:开始和结束。它在 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

那是越界访问内存。

关于c++ - EXEC BAD ACCESS 遍历 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52489179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com