To check if a specified element is present in an array in C++, you can use methods like find
or a loop to iterate through the array and compare each element.
In this example,
numbers
with values 10, 20, 30, 40, 50.find
method to check if element 30 is present in the vector.find
method returns an iterator to the element if found, otherwise it returns the end iterator.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {10, 20, 30, 40, 50};
int element = 30;
auto it = std::find(numbers.begin(), numbers.end(), element);
bool isPresent = it != numbers.end();
std::cout << "Element 30 is present: " << std::boolalpha << isPresent << std::endl;
return 0;
}
Element 30 is present: true
In this example,
fruits
with values 'apple', 'banana', 'cherry'.for
loop to iterate through the array and compare each element with the specified element 'banana'.found
to true; otherwise, it remains false.#include <iostream>
#include <string>
int main() {
std::string fruits[] = {"apple", "banana", "cherry"};
std::string element = "banana";
bool found = false;
for (const auto& fruit : fruits) {
if (fruit == element) {
found = true;
break;
}
}
std::cout << "Element 'banana' is present: " << std::boolalpha << found << std::endl;
return 0;
}
Element 'banana' is present: true
In this tutorial, we learned How to check if Specified Element is present in the Array in C++ language with well detailed examples.