How to find out if an item is present in a std::vector?

后端 未结 18 2199
滥情空心
滥情空心 2020-11-22 05:31

All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.

if ( item_present )
   do_this();
else
   do_that(         


        
18条回答
  •  粉色の甜心
    2020-11-22 06:26

    In C++11 you can use any_of. For example if it is a vector v; then:

    if (any_of(v.begin(), v.end(), bind(equal_to(), _1, item)))
       do_this();
    else
       do_that();
    

    Alternatively, use a lambda:

    if (any_of(v.begin(), v.end(), [&](const std::string& elem) { return elem == item; }))
       do_this();
    else
       do_that();
    

提交回复
热议问题