Подтвердить что ты не робот

Проверьте, найден ли элемент в массиве С++

Как проверить, есть ли у моего массива элемент, который я ищу?

В 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!");

Но в С++ я не думаю, что мне разрешено искать, если объект имеет значение null, и что будет решением С++?

4b9b3361

Ответ 1

В С++ вы должны использовать 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;
}

Ответ 2

Существует много способов: использовать алгоритм 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...
}

Ответ 3

Вы бы просто сделали то же самое, перейдя через массив, чтобы найти подходящий вам термин. Конечно, если это отсортированный массив, это будет намного быстрее, поэтому что-то похожее на prehaps:

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

Ответ 4

Для выполнения задания вы можете использовать старое программирование на языке C. Это потребует небольших знаний о С++. Хорошо для начинающих.

Для современного языка С++ вы обычно выполняете это через лямбда, функциональные объекты,... или алгоритм: find, find_if, any_of, for_each или новый синтаксис for (auto& v : container) { }. 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

Надеюсь, это поможет. Пожалуйста, обновите или добавьте, если я допустил ошибку.

Ответ 5

Если вы первоначально искали ответ на этот вопрос (значение int в отсортированном (восходящем) массиве int), вы можете использовать следующий код, который выполняет двоичный поиск (самый быстрый результат):

static inline bool exists(int ints[], int size, int k) // array, array 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));
}

edit: Также работает для несортированного массива int, если он не сортируется.