To check if a specific element is present in a list in C++, you can use the find
function of the std::list container.
In this example,
myList
with some elements.find
function to check if the specified element is present in the list.find
function returns an iterator to the element if found, otherwise it returns an iterator to the end of the list.#include <iostream>
#include <list>
int main() {
std::list<int> myList = {10, 20, 30, 40, 50};
int searchElement = 40;
auto it = std::find(myList.begin(), myList.end(), searchElement);
bool isPresent = it != myList.end();
std::cout << "Element presence in list: " << std::boolalpha << isPresent << std::endl;
return 0;
}
Element presence in list: true
In this example,
myList
with some string elements.find
function to check if the specified string is present in the list.find
function returns an iterator to the element if found, otherwise it returns an iterator to the end of the list.#include <iostream>
#include <list>
#include <string>
int main() {
std::list<std::string> myList = {"apple", "banana", "cherry", "date", "elderberry"};
std::string searchElement = "cherry";
auto it = std::find(myList.begin(), myList.end(), searchElement);
bool isPresent = it != myList.end();
std::cout << "Element presence in list: " << std::boolalpha << isPresent << std::endl;
return 0;
}
Element presence in list: true
In this tutorial, we learned How to check if a Specific Element is present in the List in C++ language with well detailed examples.