【问题标题】:signal: aborted (core dumped), making a two sum pair from a vector信号:中止(核心转储),从向量生成两个和对
【发布时间】:2021-09-02 16:28:07
【问题描述】:

这是我要解决的问题:

findTwoSumPair,它接受一个整数向量和一个 目标总和,并返回代表两个 不同 索引的对 总和为目标值的元素(索引已排序)。 这里没有明确的时间复杂度限制(即算法 只需要按预期工作)。还要确保处理空输入。

这是我的主要内容:

  std::cout << "Q3" << std::endl;
  std::vector<int> q3Input1{0, 2, 3, 4, 5};
  std::pair<int, int> q3Out1 = findTwoSumPair(q3Input1, 6);
  std::pair<int, int> q3Out2 = findTwoSumPair(q3Input1, 10);

  std::cout << q3Out1.first << " " << q3Out1.second
            << std::endl;  // should output 1 3
  std::cout << q3Out2.first << " " << q3Out2.second
            << std::endl;  // should output -1 -1

这是导致我出现问题的函数:

std::pair<int, int> findTwoSumPair(const std::vector<int>& vec, int targetSum) {
  for (unsigned int i = 0; i < vec.size(); i++){

    for(unsigned int j = i; i < vec.size();j++){
     /* 
      if(targetSum == vec[i]+ vec[j]){
      std::cout << vec[i] << vec[j];
      }*/
    }
  }
  return{vec[i],vec[j];
 // throw std::logic_error("not implemented");
}

我得到了 main.cpp,所以我不想更改它,并且有相关的库头文件可以让它运行。

由于某种原因,它只显示“Q3”。我注释掉了 if 块内的内容,因为这给了我“信号:中止(核心转储)”错误。

【问题讨论】:

  • 检查第二个 for 循环条件中使用的变量。
  • 想一想你没有找到两个加起来等于targetSum 的值的情况。在这种情况下,您返回的值是什么?他们在vec 里面吗?
  • 还要想想你在这里返回了什么。看起来您没有返回问题所要求的值:two distinct indices
  • 帮自己一个忙,从您的代码中提取minimal reproducible example。也包括在你的问题中,这样每个人都可以在没有猜测的情况下复制它。此外,在启用警告的情况下进行编译,并确保您的代码不会发出任何警告。作为这里的新用户,也请带上tour并阅读How to Ask

标签: c++ for-loop if-statement vector vec


【解决方案1】:

除了代码中的“错字”,您在内部 for 循环中测试 i 而不是 j(您当前拥有的代码将永远运行该内部循环),还有一些您的职能中的其他问题。

首先,内部循环应该从 j = i + 1 开始,否则当任何 one 值恰好是目标的一半时将找到匹配项(在您的第二个测试用例中,它将找到匹配项5 + 5,给出44的索引结果。

其次,一旦找到匹配项,该函数应返回当前的ij 值;然后,如果外部循环在没有找到匹配项的情况下终止,我们可以返回所需的{-1, -1} 信号。

这是修复了上述(和其他一些)问题的函数版本:

std::pair<int, int> findTwoSumPair(const std::vector<int>& vec, int targetSum)
{
    for (size_t i = 0; i < vec.size(); i++) {
        for (size_t j = i + 1; j < vec.size(); j++) {// Start at i + 1 and test j (not i)
            if (targetSum == vec[i] + vec[j]) {
                return{ static_cast<int>(i), static_cast<int>(j) }; // Match found
            }
        }
    }
    return { -1, -1 }; // Not found.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    相关资源
    最近更新 更多