Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a char to chars in a list in C++

Tags:

c++

Is there a way to compare a char to each element in a list of chars?

char ch;
if(ch == 'a' || ch == 'b' || ch == 'c')

Is there some way to just do

if(ch is one of {a, b, c})
like image 612
Mars Avatar asked Nov 27 '22 09:11

Mars


2 Answers

Why would you write lambdas or use a throwaway string object when you can just:

if (strchr("abc", ch))
like image 183
Ben Voigt Avatar answered Dec 05 '22 00:12

Ben Voigt


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 .

like image 24
P0W Avatar answered Dec 05 '22 02:12

P0W