Is there a way to compare a char
to each element in a list of char
s?
char ch;
if(ch == 'a' || ch == 'b' || ch == 'c')
Is there some way to just do
if(ch is one of {a, b, c})
Why would you write lambdas or use a throwaway string object when you can just:
if (strchr("abc", ch))
Use : std::any_of
With C++11 :
std::string str="abc";
if(std::any_of(str.cbegin(), str.cend(),
[ch](const char& x){return x==ch; } ))
{
}
Or use a functor:
struct comp
{
comp(char x) :ch(x){}
bool operator()(const char& x) const
{
return x == ch;
}
char ch;
};
And then,
if(std::any_of(str.cbegin(), str.cend(),comp(ch) ))
{
}
Edit : std::any_of
might not be efficient enough, just for sake of C++'s <algorithm>
one can try this out too .
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