c++ - vector<pair<int, unordered_set<int>>> 在为 pair 提供默认构造函数参数时给出段错误

标签 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 将右值定义赋予图形的第二个参数。第一个参数是 vector 的大小。我想传递一个右值,其中该对的第一个值为 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) 之后的那一行。是我的 bool 数组导致了问题。对困惑感到抱歉!我已将此帖子标记为由模组删除。

谢谢!

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

这是由于 bool 数组访问越界造成的。我应该注意到这一点,但是我尝试使用一些打印语句来查看段错误发生的位置。它在之后的行上,我猜当段错误发生时,stdout 的缓冲区没有被刷新,所以对于它之前的行,它也没有显示打印。我不会再使用 print 对我的 bug 进行二进制搜索以查找段错误 - 在这里学到了宝贵的一课。

最佳答案

是的,您遗漏了一些东西 - 段错误与 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;
}

输出(或在这里运行:https://ideone.com/kSVSnA):

1 0
0 2
0 0
0 0
0 0

您的代码中一些未定义的行为和省略的位还有其他问题 :)

关于c++ - vector<pair<int, unordered_set<int>>> 在为 pair 提供默认构造函数参数时给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39679815/

相关文章:

c++ - 如何写入第二个控制台?

c++ - 如何检查整数的二进制表示是否为回文?

c++ - 如何在 C++ 中构建与运行时版本无关的 DLL?

c++ - 从 char* 高效地实例化 vector<char>

c - 在c中打印字符串数组的第一个元素时出现段错误

c - Valgrind 报告无效的读取(和写入),但程序保持执行

c - 瑞士星历库不会在 Ubuntu 上运行

c++ - Qt安装报错

c++ - 在元组 vector 中查找特定的元组元素?

java - VB.NET 中的 vector 与列表