繁体   English   中英

向量向量的分割错误

[英]Segmentation fault with vector of vectors

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

给定一个人的列表,每个人都有一组整数,如果一个人与另一个人的共同点数大于给定阈值 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; 无论如何都不需要。

  • 在线演示,其中包含更正的代码、这些建议和一个小测试样本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM