Home > Backend Development > C++ > body text

How to Find an Element in an Array in C ?

Patricia Arquette
Release: 2024-11-11 03:14:03
Original
132 people have browsed it

How to Find an Element in an Array in C  ?

Finding an Element in an Array in C

Checking for the presence of a specific element within an array is a common programming task. In Java, this can be accomplished using the equals() method and null checks. However, in C , there is no direct equivalent of null checking for objects.

To resolve this, C employs the std::find algorithm, which searches a range of elements for a given value. By utilizing this function, you can verify whether an element exists in an array, as illustrated below:

Foo array[10];
... // Initialize the array

Foo* foo = std::find(std::begin(array), std::end(array), someObject);

if (foo != std::end(array)) {
    // Element found
    cerr << "Found at position " << std::distance(array, foo) << endl;
} else {
    // Element not found
    cerr << "Not found" << endl;
}
Copy after login

The std::find algorithm returns an iterator pointing to the first occurrence of the specified element within the specified range. If the element is not found, it returns an iterator pointing to the end of the range. By comparing the returned iterator to the end of the array, you can determine whether the element was found or not.

The above is the detailed content of How to Find an Element in an Array in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template