2015-11-12 130 views
0

我是新來的C++,並有家庭作業,我是用一維六元素矢量到解決問題。從10到101 整數我把它所以如果我輸入0,它說:「0越界」,並說「0已經輸入。所有其它號碼不在上述範圍內將打印一次消息。然而,對於0我得到它的消息六次。我只是想知道我在這裏失蹤。該方案,否則的偉大工程。TIA!當我輸入0 I得到消息「0已經進入了」 6個時代

運行並輸入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"; 
} 

回答

2

Wh帶您構建一個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

+0

好了,解釋它,謝謝大家的容易理解的解釋。 – JimiH