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

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

    You can use the find function, found in the std namespace, ie std::find. You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.

    std::find(vector.begin(), vector.end(), item) != vector.end()
    

    You're also able to dereference that iterator and use it as normal, like any other iterator.

提交回复
热议问题