2010-10-11 79 views
14

僞代碼:然後如何在數組中找到特定值並返回其索引?

int arr[ 5 ] = { 4, 1, 3, 2, 6 }, x; 

x = find(3).arr ; 

X將返回2.

+2

索引應該至少是一個無符號類型。 – GManNickG 2010-10-11 20:43:00

+1

您確定要使用索引嗎?使用某種形式的迭代器可能會更簡潔。 – 2010-10-11 21:30:15

+0

如果找不到搜索的值,您想要什麼樣的返回值? – Arun 2010-10-12 01:05:13

回答

34

你有沒有爲你的功能沒有任何意義的語法(爲什麼會返回值有一個成員叫arr?)。

要查找索引,請使用<algorithm>標題中的std::distancestd::find

int x = std::distance(arr, std::find(arr, arr + 5, 3)); 

或者你可以把它變成一個更通用的功能:

template <typename Iter> 
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x) 
{ 
    size_t i = 0; 
    while (first != last && *first != x) 
     ++first, ++i; 
    return i; 
} 

在這裏,我返回序列的長度,如果沒有找到該值(這與方式是一致的STL算法返回最後一個迭代器)。根據您的喜好,您可能希望使用其他形式的故障報告。

在你的情況,你可以使用它像這樣:

size_t x = index_of(arr, arr + 5, 3); 
2

看中的答案。使用std ::向量和性病搜索::找到

簡單的答案

使用一個for循環

+7

最好的答案:在數組上使用'std :: find()'。 – sbi 2010-10-11 20:44:34

10

這是一個非常簡單的方式通過做手工。正如Peter所說,你也可以使用<algorithm>

#include <iostream> 
int find(int arr[], int len, int seek) 
{ 
    for (int i = 0; i < len; ++i) 
    { 
     if (arr[i] == seek) return i; 
    } 
    return -1; 
} 
int main() 
{ 
    int arr[ 5 ] = { 4, 1, 3, 2, 6 }; 
    int x = find(arr,5,3); 
    std::cout << x << std::endl;  
} 
2
#include <vector> 
#include <algorithm> 

int main() 
{ 
    int arr[5] = {4, 1, 3, 2, 6}; 
    int x = -1; 
    std::vector<int> testVector(arr, arr + sizeof(arr)/sizeof(int)); 

    std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3); 
    if (it != testVector.end()) 
    { 
      x = it - testVector.begin(); 
    } 
    return 0; 
} 

或者你也可以建立一個正常方式的載體,沒有從int數組創建它,然後使用相同的解決方案如在我的例子。

1
int arr[5] = {4, 1, 3, 2, 6}; 
vector<int> vec; 
int i =0; 
int no_to_be_found; 

cin >> no_to_be_found; 

while(i != 4) 
{ 
    vec.push_back(arr[i]); 
    i++; 
} 

cout << find(vec.begin(),vec.end(),no_to_be_found) - vec.begin(); 
+0

請爲您的答案添加一些解釋,以使其對其他讀者更有用。 – 2015-06-25 08:12:44

0

我們這裏使用簡單的線性搜索。首先將索引初始化爲-1。然後搜索數組,如果找到了索引值,則分配索引變量並中斷。否則,index = -1。

int find(int arr[], int n, int key) 
    { 
    int index = -1; 

     for(int i=0; i<n; i++) 
     { 
      if(arr[i]==key) 
      { 
      index=i; 
      break; 
      } 
     } 
     return index; 
    } 


int main() 
{ 
    int arr[ 5 ] = { 4, 1, 3, 2, 6 }; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    int x = find(arr ,n, 3); 
    cout<<x<<endl; 
    return 0; 
} 
相關問題