如何检查我的数组是否有我正在寻找的元素?
在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)
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)
您只需执行相同的操作,遍历数组以搜索您想要的术语。当然,如果它是一个排序数组,这会快得多,所以类似于 prehaps:
for(int i = 0; i < arraySize; i++){
if(array[i] == itemToFind){
break;
}
}
Run Code Online (Sandbox Code Playgroud)
有很多方法......一种是使用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)