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

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

    If your vector is not ordered, use the approach MSN suggested:

    if(std::find(vector.begin(), vector.end(), item)!=vector.end()){
          // Found the item
    }
    

    If your vector is ordered, use binary_search method Brian Neal suggested:

    if(binary_search(vector.begin(), vector.end(), item)){
         // Found the item
    }
    

    binary search yields O(log n) worst-case performance, which is way more efficient than the first approach. In order to use binary search, you may use qsort to sort the vector first to guarantee it is ordered.

提交回复
热议问题