C ++变量没有正确地从向量接收新值?

时间:2017-02-02 20:16:06

标签: c++ search vector minimum

我正在尝试编写一个程序,用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;
    }
}
`

2 个答案:

答案 0 :(得分:2)

您的minimum变量未初始化,这会导致未定义的行为。它应该设置为向量中的第一个值:

minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending);

此外,ending一个接一个,这使得它选择6作为[6, 9, 8, 4]中的最小值。

因此,最终,您的代码应该如下所示:

minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending + 1); // note the + 1

虽然与问题无关,但我建议您在recursiveMinimum中使用尾部调用,explained here

start++;
return recursiveMinimum(searchVector, start, end);

答案 1 :(得分:0)

主要问题是您没有初始化minimum。因此,比较searchVector[start] < minimum可能永远不会成为现实,最小值仍然未初始化。

作为快速解决方法,请写下int minimum = MAX_INT;而不是int minimum;MAX_INT是最大正整数值(在limits.h中定义)。因此,数组中的值永远不会超过此值,并且您的最小搜索循环将起作用(除非存在其他问题;但为此,请参阅调试器:-))