Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element found in array c++

Tags:

c++

How can I check if my array has an element I'm looking for?

In Java, I would do something like this:

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

But in C++ I don't think I'm allowed to search if an Object is null so what would be the C++ solution?

like image 302
Omar Darwish Avatar asked Oct 06 '13 23:10

Omar Darwish


People also ask

How do I find a specific element in an array C++?

Using std::find_if algorithm For instance, find the index of the first 2-digit number in the array. The recommended approach is to use the std::find_if algorithm, which accepts a predicate to handle such cases. That's all about finding the index of an element in an array in C++.

How do you find if an array contains a specific string in C#?

Contains() is a string method. This method is used to check whether the substring occurs within a given string or not. It returns the boolean value. If substring exists in string or value is the empty string (“”), then it returns True, otherwise returns False.


1 Answers

In C++ you would use std::find, and check if the resultant pointer points to the end of the range, like this:

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; } 
like image 125
Sergey Kalinichenko Avatar answered Sep 19 '22 14:09

Sergey Kalinichenko