首页 > 解决方案 > 函数中的向量返回意外结果,循环

问题描述

下面预计将返回两个整数匹配的结果。我不明白为什么它会打印一些垃圾数字并且它仍然处于循环状态。

#include <vector>
#include <unordered_set>
#include <iostream>

//given array with integers {1,3,5,5,3,3} find a pair of numbers that will equal to targetSum
//target Sum=10 for example

using namespace std;
vector<int> twoNumberSum(vector<int> array, int targetSum)
{
    unordered_set<int> nums;
    for (int num: array) {
        int potentialMatch = targetSum - num;
        if (nums.find(potentialMatch) != nums.end()) {
            vector<int> a = vector<int> {num,potentialMatch};
            vector<int> b = vector<int> {potentialMatch, num};

            return potentialMatch > num ? a : b;
        } else {
            nums.insert(num);
        }
    }

}

int main() {
    vector<int> array;
    array.push_back(1);
    array.push_back(3);
    array.push_back(5);
    array.push_back(7);
    int i;
    i = 10;
    auto res = twoNumberSum(array, i);
    for (auto item : res) 
        cout << item << endl;
}

标签: c++vector

解决方案


return在函数结束之前缺少一条语句。当没有匹配时,您需要返回一个空向量。

vector<int> twoNumberSum(vector<int> array, int targetSum)
{
   unordered_set<int> nums;
   for (int num: array) {
      int potentialMatch = targetSum - num;
      if (nums.find(potentialMatch) != nums.end()) {
         vector<int> a = vector<int> {num,potentialMatch};
         vector<int> b = vector<int> {potentialMatch, num};

         return potentialMatch > num ? a : b;
      } else {
         nums.insert(num);
      }
   }

   // Missing from your code.
   return {};
}

如果没有 finalreturn语句,您的代码将具有未定义的行为。


推荐阅读