Home >Backend Development >C++ >How to Determine If an Element Exists in a C Array?
Problem:
How to ascertain if an element exists within a C array?
Solution:
In Java, the equals method can be used to compare objects for equality. However, C does not support such a method for objects. Instead, the std::find function can be employed to search for a specific element:
Foo array[10]; ... // Initialize the array // std::find returns an iterator pointing to the found element or the end of the range Foo* foo = std::find(std::begin(array), std::end(array), someObject); if (foo != std::end(array)) { // Element found std::cerr << "Found at position " << std::distance(array, foo) << std::endl; } else { // Element not found std::cerr << "Not found" << std::endl; }
Explanation:
The above is the detailed content of How to Determine If an Element Exists in a C Array?. For more information, please follow other related articles on the PHP Chinese website!