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

后端 未结 18 2422
滥情空心
滥情空心 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:04

    I've personally used templates of late to handle multiple types of containers at once rather than deal only with vectors. I found a similar example online (can't remember where) so credit goes to whoever I've pilfered this from. This particular pattern seems to handle raw arrays as well.

    template ()))>::type>
    bool contains(Container && c, T v)
    {
        return std::find(std::begin(c), std::end(c), v) != std::end(c);
    }
    

提交回复
热议问题