gpt4 book ai didi

c++ - vector vector 的段错误

转载 作者:行者123 更新时间:2023-12-02 09:56:40 29 4
gpt4 key购买 nike

运行以下代码时出现段错误。

Given a list of people each with some set of integers, the program has to find the number of friends of the first person where a person is a friend of another person if the number of integers one has in common with the other is greater than a given threshold value 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;
}

谁能告诉我哪里出错了?

最佳答案

你的计数逻辑有缺陷。这会导致无限循环。我猜你看到了一个段错误,因为你在一个类似 Hackerrank 的在线系统中,它会中断你的代码:

问题在这里:

while(i<u.size()&&j<v.size())
if(u[i]==v[j])
ctr++; // <======= once there is a match i, and j never get updated
else if(u[i]>v[j])
j++;
else
i++;

更正:
while(i<u.size()&&j<v.size())
if(u[i]==v[j]) {
ctr++;
i++; j++; // <--- skip the matching elements
}
else if(u[i]>v[j])
j++;
else
i++;

删除 push_back() 后问题消失了。如您的评论中所述,因为比较循环将立即结束。

不相关 :
  • 考虑避免使用可变长度数组,因为它们不是标准的 C++。所以而不是bool isfriend[n];更喜欢 vector<bool> isfriend(n, false);这样做的好处是避免您必须编写一个 for 循环来初始化值。
  • 避免命名变量null .这令人困惑。所以删除语句B null;无论如何都不需要。
  • Online demo更正您的代码和这些建议以及一个小测试样本。
  • 关于c++ - vector vector 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59544235/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com