how to cehck if list has element c++
To check if a list has a specific element in C++, you can iterate through the list and compare each element with the target element. Here is an example of how you can do this:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {1, 2, 3, 4, 5};
int target = 3;
bool found = false;
// Iterate through the list
for (const auto& element : myList) {
// Compare each element with the target
if (element == target) {
found = true;
break;
}
}
if (found) {
std::cout << "Element " << target << " is found in the list." << std::endl;
} else {
std::cout << "Element " << target << " is not found in the list." << std::endl;
}
return 0;
}
In this example, we have a list named myList
with elements 1, 2, 3, 4, and 5. We want to check if the list contains the element 3.
We declare a boolean variable found
and initialize it as false
. This variable will be used to keep track of whether the target element is found in the list.
We iterate through the list using a range-based for loop. For each element in the list, we check if it is equal to the target element using the ==
operator. If a match is found, we set the found
variable to true
and break out of the loop using the break
statement.
After the loop, we check the value of the found
variable. If it is true
, we print a message indicating that the element is found in the list. Otherwise, we print a message indicating that the element is not found in the list.
This approach allows you to check if a list contains a specific element in C++.