2013-10-06 17 views
16

如何檢查我的數組是否有我正在查找的元素?檢查在數組C++中找到的元素

在Java中,我會做這樣的事情:

Foo someObject = new Foo(someParameter); 
Foo foo; 
//search through Foo[] arr 
for(int i = 0; i < arr.length; i++){ 
    if arr[i].equals(someObject) 
    foo = arr[i]; 
} 
if (foo == null) 
    System.out.println("Not found!"); 
else 
    System.out.println("Found!"); 

但在C++中,我不認爲我被允許搜索對象是否是空,因此這將是C++的解決方案?

回答

36

在C++中應該使用std::find,如果所得到的指針指向選中的範圍的端部,這樣的:

Foo array[10]; 
... // Init the array here 
Foo *foo = std::find(std::begin(array), std::end(array), someObject); 
// When the element is not found, std::find returns the end of the range 
if (foo != std::end(array)) { 
    cerr << "Found at position " << std::distance(array, foo) << endl; 
} else { 
    cerr << "Not found" << endl; 
} 
+1

'10'從哪裏來? –

+1

@JamesMcMahon這是我在示例中爲數組大小選擇的任意數字。 – dasblinkenlight

+0

因爲它被用作重複的目標,並且C++ 11現在已經有5年了,所以考慮用'std :: end(array)'替換'array + 10'? – Yakk

-4

C++有NULL爲好,經常是相同的爲0(指針來解決00000000)。

Do you use NULL or 0 (zero) for pointers in C++?

所以在C++是空檢查將是:

if (!foo) 
    cout << "not found"; 
+0

當我嘗試這種方式時,它說「!操作符」找不到我的對象。 –

+0

或者你可以嘗試(foo == NULL) – canhazbits

3

你只想做同樣的事情,通過數組循環來搜索你想要的期限。當然,如果它是一個有序數組,這將是更快,這樣類似的東西prehaps:

for(int i = 0; i < arraySize; i++){ 
    if(array[i] == itemToFind){ 
     break; 
    } 
} 
6

有很多方法......一個是使用std::find()算法,例如

#include <algorithm> 

int myArray[] = { 3, 2, 1, 0, 1, 2, 3 }; 
size_t myArraySize = sizeof(myArray)/sizeof(int); 
int *end = myArray + myArraySize; 
// find the value 0: 
int *result = std::find(myArray, end, 0); 
if (result != end) { 
    // found value at "result" pointer location... 
} 
2

您可以使用舊的C風格編程來完成這項工作。這將需要很少的關於C++的知識。適合初學者。 findfind_ifany_offor_each,或新for (auto& v : container) { }語法:

對於現代C++語言中,你通常是通過拉姆達,函數對象,...或算法做到這一點。 find類算法需要更多的代碼行。您也可以根據您的特定需求爲您編寫自己的模板find功能。

這裏是我的示例代碼

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

using namespace std; 

/** 
* This is old C-like style. It is mostly gong from 
* modern C++ programming. You can still use this 
* since you need to know very little about C++. 
* @param storeSize you have to know the size of store 
* How many elements are in the array. 
* @return the index of the element in the array, 
* if not found return -1 
*/ 
int in_array(const int store[], const int storeSize, const int query) { 
    for (size_t i=0; i<storeSize; ++i) { 
     if (store[i] == query) { 
     return i; 
     } 
    } 
    return -1; 
} 

void testfind() { 
    int iarr[] = { 3, 6, 8, 33, 77, 63, 7, 11 }; 

    // for beginners, it is good to practice a looping method 
    int query = 7; 
    if (in_array(iarr, 8, query) != -1) { 
     cout << query << " is in the array\n"; 
    } 

    // using vector or list, ... any container in C++ 
    vector<int> vecint{ 3, 6, 8, 33, 77, 63, 7, 11 }; 
    auto it=find(vecint.begin(), vecint.end(), query); 
    cout << "using find()\n"; 
    if (it != vecint.end()) { 
     cout << "found " << query << " in the container\n"; 
    } 
    else { 
     cout << "your query: " << query << " is not inside the container\n"; 
    } 

    using namespace std::placeholders; 
    // here the query variable is bound to the `equal_to` function 
    // object (defined in std) 
    cout << "using any_of\n"; 
    if (any_of(vecint.begin(), vecint.end(), bind(equal_to<int>(), _1, query))) { 
     cout << "found " << query << " in the container\n"; 
    } 
    else { 
     cout << "your query: " << query << " is not inside the container\n"; 
    } 

    // using lambda, here I am capturing the query variable 
    // into the lambda function 
    cout << "using any_of with lambda:\n"; 
    if (any_of(vecint.begin(), vecint.end(), 
      [query](int val)->bool{ return val==query; })) { 
     cout << "found " << query << " in the container\n"; 
    } 
    else { 
     cout << "your query: " << query << " is not inside the container\n"; 
    } 
} 

int main(int argc, char* argv[]) { 
    testfind(); 

    return 0; 
} 

說這個文件被命名爲 'testalgorithm.cpp' 你需要

g++ -std=c++11 -o testalgorithm testalgorithm.cpp 

希望這將有助於進行編譯。如果我犯了錯誤,請更新或添加。

1

如果您最初尋找的答案this question (int value in sorted (Ascending) int array),那麼你可以使用下面的代碼執行二進制搜索(最快結果):

static inline bool exists(int ints[], int size, int k) // array, array's size, searched value 
{ 
    if (size <= 0)  // check that array size is not null or negative 
     return false; 
    // sort(ints, ints + size); // uncomment this line if array wasn't previously sorted 
    return (std::binary_search(ints, ints + size, k)); 
} 

編輯:也適用於未分類的int數組,如果取消註釋排序。