信号:中止(核心转储),从向量形成一个二和对

signal: aborted (core dumped), making a two sum pair from a vector

提问人:Funmi Orekoya 提问时间:9/3/2021 最后编辑:Adrian MoleFunmi Orekoya 更新时间:9/3/2021 访问量:1762

问:

这是我试图解决的问题:

Write ,它接受一个整数向量和 target sum,并返回表示两个不同索引的对 总和为目标值的元素(对索引进行排序)。 这里没有明确的时间复杂度约束(即算法 只需要按预期工作)。此外,请确保处理空输入。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

C++ for 循环 if 语句 向量 vec

评论

3赞 1201ProgramAlarm 9/3/2021
检查第二个 for 循环条件中使用的变量。
0赞 Martin York 9/3/2021
想一想你找不到两个加起来等于 的值的情况。在这种情况下,您返回的值是什么?他们在里面吗?targetSumvec
0赞 Martin York 9/3/2021
还要想想你要在这里返回什么。看起来您没有返回问题要求的值:two distinct indices
1赞 Ulrich Eckhardt 9/3/2021
帮自己一个忙,从你的代码中提取一个最小的可重现的例子。还要将其包含在您的问题中,以便每个人都可以在不猜测的情况下重现它。此外,在启用警告的情况下进行编译,并确保代码不会发出任何警告。作为这里的新用户,也请参加导览并阅读如何提问

答:

0赞 Adrian Mole 9/3/2021 #1

除了代码中的“错别字”之外,您在内部循环中进行测试,而不是(您当前拥有的代码将永远运行该内部循环),您的函数中还有一些其他问题。iforj

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

其次,一旦找到匹配项,函数就应该返回当前和值;然后,如果外部环路在没有找到匹配项的情况下终止,我们可以返回所需的信号。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.
}