Is there a find()
function for list as there was in vector?
Is there a way to do that in list?
In std::find() you can pass two iterators and a value. It will iterate all the elements between 2 given iterators and compare the given val with each one. If any match is found, then it will immediately return that iterator, else it returns the iterator pointing to end of list.
find() function is an inbuilt function in C++ STL, which is defined in header file. This function is used to find an element or a value in a set container. find() returns an iterator which points to the position of the element which is searched.
Use the any_of() Function to Check if an Array Contains an Element in C++ We can use the any_of() function to check if a predicate conforms to any elements present in a given range. If yes, it returns true ; else, it returns false .
You use std::find
from <algorithm>
, which works equally well for std::list
and std::vector
. std::vector
does not have its own search/find function.
#include <list> #include <algorithm> int main() { std::list<int> ilist; ilist.push_back(1); ilist.push_back(2); ilist.push_back(3); std::list<int>::iterator findIter = std::find(ilist.begin(), ilist.end(), 1); }
Note that this works for built-in types like int
as well as standard library types like std::string
by default because they have operator==
provided for them. If you are using using std::find
on a container of a user-defined type, you should overload operator==
to allow std::find
to work properly: EqualityComparable
concept
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With