2014-01-09 30 views
2
int search(vector<int>& numbers, int numToFind){ 
    int numberSize = numbers.size(); 
    for (int i = 0; i < numberSize; i++){ 
     if(numbers.at(i) == numToFind){ 
      return i; 
     } 
     else{ 
      return -1; 
     } 
    } 
} 

我的功能搜索應該搜索numToFind的矢量,如果找到它,它會返回位置。但是,當我運行這個函數時,它一直給我-1。如何通過向量進行搜索並獲取C++中元素的位置?

+4

他們排序? '的std :: binary_search'。否則,'std :: find'。沒有理由自己編碼。但至少使矢量「const」。你不要修改它。 – chris

+0

它們未排序,例如3 10 9 2 5 0. –

+0

'狐狸'是什麼?看起來你應該比較'numToFind'。 – MikeD

回答

5

你太早返回-1。你的函數甚至不搜索矢量的其餘部分。

int search(std::vector<int>& numbers, int numToFind){ 
    int numberSize = numbers.size(); 
    for (int i = 0; i < numberSize; i++){ 
     if(numbers.at(i) == numToFind){ 
      return i; 
     } 
     // A return statement here would cut the loop too early 
    } 
    return -1; // Didn't find anything 
} 

如果您想要基於one的索引,請改爲返回i + 1

相關問題