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

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

    With boost you can use any_of_equal:

    #include <boost/algorithm/cxx11/any_of.hpp>
    
    bool item_present = boost::algorithm::any_of_equal(vector, element);
    
    0 讨论(0)
  • 2020-11-22 06:20

    You can use std::find from <algorithm>:

    #include <vector>
    vector<int> vec; 
    //can have other data types instead of int but must same datatype as item 
    std::find(vec.begin(), vec.end(), item) != vec.end()
    

    This returns a bool (true if present, false otherwise). With your example:

    #include <algorithm>
    #include <vector>
    
    if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
       do_this();
    else
       do_that();
    
    0 讨论(0)
  • 2020-11-22 06:20

    I use something like this...

    #include <algorithm>
    
    
    template <typename T> 
    const bool Contains( std::vector<T>& Vec, const T& Element ) 
    {
        if (std::find(Vec.begin(), Vec.end(), Element) != Vec.end())
            return true;
    
        return false;
    }
    
    if (Contains(vector,item))
       blah
    else
       blah
    

    ...as that way it's actually clear and readable. (Obviously you can reuse the template in multiple places).

    0 讨论(0)
  • 2020-11-22 06:21

    As others have said, use the STL find or find_if functions. But if you are searching in very large vectors and this impacts performance, you may want to sort your vector and then use the binary_search, lower_bound, or upper_bound algorithms.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 06:21

    Use the STL find function.

    Keep in mind that there is also a find_if function, which you can use if your search is more complex, i.e. if you're not just looking for an element, but, for example, want see if there is an element that fulfills a certain condition, for example, a string that starts with "abc". (find_if would give you an iterator that points to the first such element).

    0 讨论(0)
提交回复
热议问题