list.push_back的分段错误

时间:2019-02-13 12:55:33

标签: c++ segmentation-fault

我被困在一个似乎超出我的知识水平的错误上。

代码是用于破解编码采访任务04_07的算法。我们必须在其中找出项目的依赖关系结构。

作为数据结构,我使用带有整数的列表向量:vector<list<int>>

在推送后访问元素是可以的。 但是,当我稍后进行此操作时,我在deps.at(i).push_back(-1)遇到了分段错误。

非常感谢您的帮助:)由于我没有使用任何指针或手动内存管理,因此我的线索特别少。

这是完整的代码,它是整个程序:

int projects = 6;
vector<list<int>> deps;

for(int i=1; i<=projects; i++)
{
    list<int> l;
    deps.push_back(l);
}

deps[4].push_back(1);
deps[2].push_back(6);
deps[4].push_back(2);
deps[1].push_back(6);
deps[3].push_back(4);

for(auto c: deps)
    cout << c.back() << endl;

vector<int> buildOrder;

while(buildOrder.size() < projects)
{
    for(int i = 1; i <= projects; i++)
    {
        if(deps[i].size() == 0)
        {
            buildOrder.push_back(i);

            deps.at(i).push_back(-1);


            for(int j=1; j <= projects; j++)
            {
                list<int>::iterator iter = find(deps[j].begin(), deps[j].end(), i);
                if(iter != deps[j].end()) deps[j].erase(iter);
            }

        }
    }
}

for(int p : buildOrder) cout << p << " ";
cout << endl;

0 个答案:

没有答案