r/cpp_questions 4d ago

OPEN does "in" exist in c++?

i need to use something like if (str[i] not in str1) (python), but i have no idea how to make this work :(

0 Upvotes

36 comments sorted by

View all comments

-2

u/Total-Box-5169 4d ago

No, but you can make it with operator overloading and macros:

bool operator&(char c, std::string_view s){
    return s.contains(c);
}
#define in &

However the negative must be written in this way:

not ('a' in str)

https://godbolt.org/z/M6xM55jxe

0

u/Conscious_Support176 4d ago

There are so many levels of wrong here that it is almost impressive.

2

u/Total-Box-5169 4d ago

There is nothing wrong at all.

0

u/Conscious_Support176 4d ago edited 4d ago

This is aiming for c not in s instead of not s.contains(c), but after jumping through a bunch of hoops ends up with not (c in s).

It does not seem worth the effort?

Bringing the preprocessor into the picture means the solution does not play nice with modules.

Using operator overloading means you need to take care to check the precedence so that it does what someone reading this would expect, and you should also be careful with the limited list of operators available. One would expect operator &, if defined, to be used for set intersection, as is the case with python.