c++ - 函数中的向量返回意外结果,循环
问题描述
下面预计将返回两个整数匹配的结果。我不明白为什么它会打印一些垃圾数字并且它仍然处于循环状态。
#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;
}
解决方案
您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
语句,您的代码将具有未定义的行为。
推荐阅读
- c++ - Qt 读取文本文件的一些信息
- java - 如何在 t[][] 中对 a[] 中的 int 进行随机排序,使 a[] 中的所有 int 彼此相邻?
- c++ - 覆盖自定义数组类的运算符/开始/结束
- ide - Goland IDE 中的“...处没有代码”错误
- haskell - 使用 StateT s IO a 的内存泄漏在哪里?
- python - 在 azure cosmos db 上创建集合太慢
- linux - 在 Python 中检测控制台上按下的箭头键
- android - android thread.join() 没有按预期工作
- java - 这种反转链表的方法有问题吗
- c# - 如何在 MVP 项目中填充 DataGridView?