Check if element is in the list (contains)
std::list
does not provide a search method. You can iterate over the list and check if the element exists or use std::find
. But I think for your situation std::set
is more preferable. The former will take O(n)
time but later will take O(lg(n))
time to search.
You can simply use:
int my_var = 3;
std::set<int> mySet {1, 2, 3, 4};
if(mySet.find(myVar) != mySet.end()){
//do whatever
}
They really should add a wrapper. Like this:
namespace std
{
template<class _container,
class _Ty> inline
bool contains(_container _C, const _Ty& _Val)
{return std::find(_C.begin(), _C.end(), _Val) != _C.end(); }
};
...
if( std::contains(my_container, what_to_find) )
{
}
you must #include <algorithm>
, then you can use std::find
You can use std::find
bool found = (std::find(my_list.begin(), my_list.end(), my_var) != my_list.end());
You need to include <algorithm>
. It should work on standard containers, vectors lists, etc...