提问者:小点点

检查是否在数组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++的解决方案是什么呢?


共3个答案

匿名用户

在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;
}

匿名用户

有很多种方法。。。一种是使用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...
}

匿名用户

你只需要做同样的事情,在数组中循环搜索你想要的词。当然,如果它是一个排序数组,这会快得多,所以类似于preaphs:

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

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(检查|数组|c++|中找到|元素)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?