vector <pair <int,unordered_set <int =“”>&gt;&gt;在为

时间:2016-09-24 18:48:12

标签: c++ vector segmentation-fault rvalue

**编辑:默认构造函数不会导致问题。我在下面说明了原因。我已经标记并投票决定关闭这个问题,对于现在有机会担任此职位的人道歉。 **

无效的代码

int n = numCourses;
vector<pair<int, unordered_set<int>>> graph(n, make_pair(0, unordered_set<int>())); // pair of how many edges go in, and set of its neighbors.
// We have to find our leaves:
bool leaf[n];
for(int i = 0; i < n; i++){
    leaf[i] = true;
}

for(auto p : prerequisites){
    graph[p.first].first++;
    graph[p.first].second.insert(0);
    leaf[p.second] = false;
}

vector<int> leaves;
for(int i = 0; i < n; i++){
    if(leaf[i])
        leaves.push_back(i);
}

我正在尝试构建一个具有一些不错属性的DAG图。我想在图中提供一个默认的构造函数参数,使用make_pair将rvalue定义赋予graph的第二个参数。第一个参数是向量的大小。我想传递一个rvalue,其中该对的第一个值为0,所以当我在graph[p.first].first++递增时我确定它是0。

我尝试了这个,当它到达graph[p.first].second.insert(0)时,它会抛出一个段错误,但我不能100%确定它为什么会发生。

可行的代码

int n = numCourses;
vector<pair<int, unordered_set<int>>> graph(n); // NO MORE DEFAULT RVALUE
// We have to find our leaves:
bool leaf[n];
for(int i = 0; i < n; i++){
    leaf[i] = true;
}

for(auto p : prerequisites){
    graph[p.first].first++;
    graph[p.first].second.insert(0); 
    leaf[p.second] = false;
}

vector<int> leaves;
for(int i = 0; i < n; i++){
    if(leaf[i])
        leaves.push_back(i); // This causes a segfault if I don't change it.
}

所以问题实际上就在graph[p.first].second.insert(0)之后。这是我的布尔数组引起的问题。对困惑感到抱歉!我已标记此帖子将被mod删除。

谢谢!

编辑:下面我添加了一些可运行的案例: 不会导致段错误:https://ideone.com/EdmSva 是否导致段错误:https://ideone.com/GHQfog

这是由于布尔数组访问越界。我应该接受这个,但是我尝试使用一些打印语句来查看segfault发生的位置。它是在线后,我猜测当发生段错误时,stdout的缓冲区没有刷新,所以对于该行,它也没有显示打印。我将不再使用print来二进制搜索我的错误以获取段错误了 - 在这里学到了宝贵的一课。

1 个答案:

答案 0 :(得分:2)

是的,你遗漏了一些东西 - 段错误与graph的初始化无关,而#include <iostream> #include <vector> #include <unordered_set> using namespace std; int main() { // your code goes here int n = 5; vector<pair<int, unordered_set<int>>> graph(n, make_pair(0, unordered_set<int>())); graph[0].first = 1; graph[1].second.insert(5); graph[1].second.insert(6); for (auto&& p : graph) { std::cout << p.first << " " << p.second.size() << std::endl; } return 0; } 的初始化与人们期望的完全一样。签出的简单示例:

1 0
0 2
0 0
0 0
0 0

输出(或在此处运行:https://ideone.com/kSVSnA):

collections.Counter

在某些未定义的行为中出现了其他错误,并在代码中省略了一些内容:)

相关问题