Check whether an element is in std::initializer_list
If you have access to c++20 you can use set
's contains
which returns a bool
allowing you to do:
if(set{ 4, 8, 15, 16, 23, 42 }.contains(x))
Live Example
Otherwise, with just c++11 you can still use set
's count
which only returns 1 or 0 allowing you to do something like:
if(set<int>{ 4, 8, 15, 16, 23, 42 }.count(x) > 0U)
Live Example
Keep in mind that magic numbers can be confusing for your audience (and cause 5 seasons of Lost.)
I'd recommend declaring your numbers as a const initializer_list<int>
and giving them a meaningful name:
const auto finalCandidates{ 4, 8, 15, 16, 23, 42 };
if(cend(finalCandidates) != find(cbegin(finalCandidates), cend(finalCandidates), x))
boost::algorithm::contains
doesn't only work on strings, it works on any range, i.e. a sequence that can yield a begin and end iterator. To find a single value use it as follows:
auto l = {1,2,3,4};
auto l1 = {2}; // thing you want to find
if(boost::algorithm::contains(l, l1)) { ... }
You can perform your search using the standard library only, but doing so is quite a bit more verbose. A couple of options are:
using a lambda
if(std::any_of(l.begin(), l.end(), [](int i){ return i == 2; })) { ... }
using
std::bind
using std::placeholders::_1; if(std::any_of(l.begin(), l.end(), std::bind(std::equal_to<>(), 2, _1)) { ... }
Live demo
Note that std::equal_to<>()
is a C++14-only option. For a C++11 compiler, use std::equal_to<int>()
.