【发布时间】:2017-06-20 01:46:36
【问题描述】:
我正在尝试编写一个程序,该程序创建并用 int 值填充向量,然后搜索它并递归返回最小值。我已经编写并构建了代码,但它每次都会返回一个非常大的最小值——我觉得它没有正确地将最小值分配给int minimum,但我不确定。有什么想法吗?
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
int vectorSize;
int minimum;
int result = -1;
int start;
int ending;
int answer;
int test;
int recursiveMinimum(vector<int>, int, int);
void main() {
cout << "How many values do you want your vector to be? ";
cin >> vectorSize;
cout << endl;
vector<int> searchVector(vectorSize);
start = 0;
ending = searchVector.size() - 1;
for (int i = 0; i < vectorSize; i++) {
cout << "Enter value for position " << i << " " << endl;
cin >> searchVector[i];
}
for (int x = 0; x < vectorSize; x++) {
cout << searchVector[x] << " ";
}
int answer = recursiveMinimum(searchVector, start, ending);
cout << "The smallest value in the vector is: " << answer;
_getch();
}
int recursiveMinimum(vector<int> searchVector, int start, int end) {
if (start < end) {
if (searchVector[start] < minimum) {
minimum = searchVector[start]; //this part seems to not work
}
start++;
recursiveMinimum(searchVector, start, end);
}
else {
return minimum;
}
}
`
【问题讨论】:
-
不需要递归来找到向量中的最小值。你可以遍历(一个未排序的向量)并在 O(N) 中找到它,如果它是排序的,你可以在 O(1) 中找到它。
-
听起来你可能需要学习如何使用调试器来单步调试你的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。延伸阅读:How to debug small programs
-
另外,您确实应该通过引用传递向量以避免复制。