当我输入0时,我收到消息“0已经输入”6次

时间:2015-11-12 03:11:17

标签: c++

我是c +的新手并且有一个家庭作业,我将使用一维六元素向量来解决问题。整数从10到101。 我设置它,所以如果我输入0,它说“0超出界限”,并说“0已经输入。所有其他数字不在上述范围内将打印消息一次。但是对于0,我得到它的消息六次。我只是想知道我在这里缺少什么。这个程序效果很好.TIA !!

运行它并输入0后我得到

0 is out of bounds
0 has been entered
0 has been entered
0 has been entered
etc.
please enter a number

我有3个单独的文件用于家庭作业。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

Selection::Selection()
{

}
bool Selection::checknumber(int n) const
{
    if (n < 10 || n > 101)
    {
        cerr << "\nNumber\n" << n << " is out of bounds.\n";
        return false;
    }
    else
        return true;
}
bool Selection::checkvector(const vector<int> &v, int n)
{
    bool check = true;
    for (size_t j = 0; j < v.size(); ++j)
    {
        if (n == v[j])
        {
            cerr << "\nNumber " << n << " has already been entered.\n";
            check = false;
        }
    }
    return check;
}
void Selection::displayvector(vector<int> &v) const
{
    cout << "\nThe numbers in the vector are: ";
    for (int item : v)
    {
        cout << item << " ";
    }
}
void Selection::menu()
{
    const size_t size = 6;
    vector<int>name(size);
    for (size_t i = 0; i < name.size(); ++i)
    {
        int number = 40;
        bool cont = false;
        while (cont == false)
        {
            cout << "Please enter a number:\n";
            cin >> number;
            bool cont1 = checknumber(number);
            bool cont2 = checkvector(name, number);
            if (cont1 == false || cont2 == false)
            {
                cont = false;
            }
            else
                cont = true;
        }
        name[i] = number;

    }
    sort(name.begin(), name.end());
    displayvector(name);

    int input = 10;
    while (input >= 0)
    {
        bool position = false;
        cout << "\nPlease enter a number to search in vector OR a negative number to exit: ";
        cin >> input;
        if (input < 0)
            break;
        bool found = binary_search(name.begin(), name.end(), input);
        cout << endl << input << (found ? " was " : " was not ") << "found in the vector";
    }
    cout << "\n\nGoodbye\n";
}

1 个答案:

答案 0 :(得分:2)

构建std::vector时的大小与您在以下行中的大小相同

std::vector<int> name(size);

vector中的所有元素都将默认初始化,具体取决于使用的类型。在这种情况下,您使用了int,因此所有元素都将是0

由于您在调用

时从未更改过这些元素
checkvector(name, number);

并传递0(作为number),它会匹配vector中的所有元素。

您需要提供vector个不同的默认值,或者不允许传入0。或者,您可以构建一个空的vector,并且在传递唯一数字时,您可以将它们添加到vector

bool Selection::checkvector(const vector<int> &v, int n)
{
    // Check if our vector contains this number.
    if (std::find(v.begin(), v.end(), n) != v.end())
    {
        // n was found in v
        cerr << "\nNumber " << n << " has already been entered.\n";
        return false;
    }
    else
    {
        // n was not found, so add it. This will increase the vector's size by 1.
        v.push_back(n);
        return true;
    }
}

我使用std::find在容器中搜索n,而不是遍历每个元素。