Check if element is in the list (contains)

后端 未结 7 1941
南笙
南笙 2021-01-31 14:38

I\'ve got a list of elements, say, integers and I want to check if my variable (another integer) is one of the elements from the list. In python I\'d do:

my_list         


        
7条回答
  •  隐瞒了意图╮
    2021-01-31 15:08

    A one-liner solution, similar to python, would be (std::set {1, 2, 3, 4}).count(my_var) > 0.

    Minimal working example

    int my_var = 3;
    bool myVarIn = (std::set {1, 2, 3, 4}).count(my_var) > 0;
    std::cout << std::boolalpha << myVarIn << std::endl;
    

    prints true or false dependent of the value of my_var.

提交回复
热议问题