检查是否在数组c ++中找到了元素

Oma*_*ish 22 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!");
Run Code Online (Sandbox Code Playgroud)

但是在C++中我不认为我可以搜索一个Object是否为null所以C++解决方案是什么?

das*_*ght 56

在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;
}
Run Code Online (Sandbox Code Playgroud)

  • @JamesMcMahon 这是我在示例中为数组大小选择的任意数字。 (3认同)
  • 由于这被用作重复目标,而 C++11 现在已有 5 年历史,是否考虑用 `std::end(array)` 替换 `array+10`? (2认同)
  • 如果有人对最后一个元素和结束感到困惑,结束实际上是一个过去的元素,是数组中最后一个元素后面的理论元素。它不指向任何元素,因此不应取消引用。 (2认同)

And*_*kha 12

这是一个简单的通用 C++11 函数contains,适用于数组和容器:

using namespace std;

template<class C, typename T>
bool contains(C&& c, T e) { return find(begin(c), end(c), e) != end(c); };
Run Code Online (Sandbox Code Playgroud)

简单的用法contains(arr, el)有点类似于inPython中的关键字语义。

这是一个完整的演示:

#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <iostream>

template<typename C, typename T>
bool contains(C&& c, T e) { 
    return std::find(std::begin(c), std::end(c), e) != std::end(c);
};

template<typename C, typename T>
void check(C&& c, T e) {
    std::cout << e << (contains(c,e) ? "" : " not") <<  " found\n";
}

int main() {
    int a[] = { 10, 15, 20 };
    std::array<int, 3> b { 10, 10, 10 };
    std::vector<int> v { 10, 20, 30 };
    std::string s { "Hello, Stack Overflow" };
    
    check(a, 10);
    check(b, 15);
    check(v, 20);
    check(s, 'Z');

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

10 found
15 not found
20 found
Z not found
Run Code Online (Sandbox Code Playgroud)


Riv*_*asa 9

您只需执行相同的操作,遍历数组以搜索您想要的术语。当然,如果它是一个排序数组,这会快得多,所以类似于 prehaps:

for(int i = 0; i < arraySize; i++){
     if(array[i] == itemToFind){
         break;
     }
}
Run Code Online (Sandbox Code Playgroud)


Kev*_*ant 7

有很多方法......一种是使用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...
}
Run Code Online (Sandbox Code Playgroud)