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?
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++.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With