lundi 24 septembre 2018

EXEC BAD ACCESS Iterating through vector

I have the following code which is trying to iterate through a vector. It takes as parameters a value, and two iterators: start and end. It is failing specifically on while (start_iter != end_iter) throwing a EXC_BAD_ACCESS error code 1.

Here is the code where it blows up:

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();
}

And here is the code that calls it:

// 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;
}

Aucun commentaire:

Enregistrer un commentaire