【发布时间】:2020-04-19 23:46:46
【问题描述】:
运行以下代码时出现分段错误。
给定一个人列表,每个人都有一组整数,如果一个人与另一个人共有的整数个数是大于给定阈值K
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
class B {
public:
vector<int> b;
B() { b.reserve(301); }
};
int count(vector<int> u, vector<int> v) // To count the number of integers one
// vector has with the other
{
sort(u.begin(), u.end());
sort(v.begin(), v.end());
int i = 0, j = 0, ctr = 0;
while (i < u.size() && j < v.size())
if (u[i] == v[j])
ctr++;
else if (u[i] > v[j])
j++;
else
i++;
return ctr;
}
int main() {
B null;
int n, k, p, temp,
ctr = 0; // n is number of people and k is the threshold value
cin >> n >> k;
vector<B> id;
id.resize(n);
bool isfriend[n];
for (int i = 0; i < n; i++) {
cin >> p; // p is the number of integers for the person i
for (int j = 0; j < p; j++) {
cin >> temp;
id[i].b.push_back(
temp); // If this line is removed, there is no segmentation fault
}
}
for (int i = 0; i < n; i++)
isfriend[i] = false;
isfriend[0] = true;
queue<int> q;
q.push(0);
while (q.empty() == false) {
p = q.front();
q.pop();
for (int i = 0; i < n; i++)
if (isfriend[i] == false) {
temp = count(id[p].b, id[i].b);
if (temp >= k) {
ctr++;
q.push(i);
isfriend[i] = true;
}
}
}
cout << ctr; // No. of friends of person 0
return 0;
}
谁能告诉我哪里出错了?
【问题讨论】:
-
您好,请问您是用GDB解决的吗?
-
获取回溯,是的。但是,错误变得明显的点可能与导致错误的点不同。无论如何,对于此处的有效问题,您需要提取并提供minimal reproducible example。确保它不包含不必要的代码并且不需要手动交互。作为新用户,也可以使用tour 并阅读How to Ask。
-
您能否提供一些示例输入,说明哪种情况会导致分段错误
标签: c++ multidimensional-array vector segmentation-fault dynamic-arrays