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

1.8k Views Asked by At

This is the question I'm trying to solve:

Write findTwoSumPair, which takes in a vector of integers and a target sum, and returns a pair that represents two distinct indices of elements that sum up to the target value (with indexes sorted). There are no explicit time complexity constraints here (i.e. algorithm just needs to work as intended). Also make sure to handle empty input.

This is my main:

  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

And this is the function causing me problems:

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");
}

I was given the main.cpp so I'd like to not change it and there are the relevant library headers to make it run.

It only shows "Q3" for some reason. I commented out the content inside the if block because that was giving me the "signal: aborted (core dumped)" error.

1

There are 1 best solutions below

0
On

As well as the "typo" in your code, where you are testing i in the inner for loop instead of j (the code you currently have will run that inner loop forever), there are some other issues in your function.

First, that inner loop should start at j = i + 1, otherwise a match will be found when any one value is exactly half the target (in your second test case, it will find a match for 5 + 5, giving index results of 4 and 4).

Second, as soon as a match is found, the function should return the current i and j values; then, if the outer loop terminates without a match being found, we can return the required {-1, -1} signal.

Here's a version of your function with the aforementioned (and some other) issues fixed:

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.
}