首页 文章

如何确定某个项目是否存在于std :: vector中?

提问于
浏览
533

我想要做的就是检查一个元素是否存在于向量中,所以我可以处理每个案例 .

if ( item_present )
   do_this();
else
   do_that();

17 回答

  • 19

    使用stl的算法头中的find . 我已经用int类型说明了它的用法 . 您可以使用您喜欢的任何类型,只要您可以比较相等(如果您需要自定义类,则重载==) .

    #include <algorithm>
    #include <vector>
    
    using namespace std;
    int main()
    {   
        typedef vector<int> IntContainer;
        typedef IntContainer::iterator IntIterator;
    
        IntContainer vw;
    
        //...
    
        // find 5
        IntIterator i = find(vw.begin(), vw.end(), 5);
    
        if (i != vw.end()) {
            // found it
        } else {
            // doesn't exist
        }
    
        return 0;
    }
    
  • 2

    使用boost,您可以使用any_of_equal

    #include <boost/algorithm/cxx11/any_of.hpp>
    
    bool item_present = boost::algorithm::any_of_equal(vector, element);
    
  • 5

    如果你想在向量中找到一个字符串:

    struct isEqual
    {
        isEqual(const std::string& s): m_s(s)
        {}
    
        bool operator()(OIDV* l)
        {
            return l->oid == m_s;
        }
    
        std::string m_s;
    };
    struct OIDV
    {
        string oid;
    //else
    };
    VecOidv::iterator itFind=find_if(vecOidv.begin(),vecOidv.end(),isEqual(szTmp));
    
  • 3

    正如其他人所说,使用STL findfind_if函数 . 但是,如果要搜索非常大的向量并且这会影响性能,则可能需要对向量进行排序,然后使用binary_searchlower_boundupper_bound算法 .

  • 10

    请记住,如果您要进行大量查找,那么有更好的STL容器 . 我不知道你的应用程序是什么,但像std :: map这样的关联容器可能值得考虑 .

    std :: vector是选择的容器,除非你有另一个的理由,并且按值查找可能是这样的原因 .

  • 34

    在C 11中,您可以使用 any_of . 例如,如果它是 vector<string> v; 则:

    if (any_of(v.begin(), v.end(), bind2nd(equal_to<string>(), item)))
       do_this();
    else
       do_that();
    
  • 6

    使用Newton C++它比使用std :: find更容易,自我记录并且更快,因为直接返回bool .

    bool exists_linear( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )
    
    bool exists_binary( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )
    

    我认为这些功能显而易见 .

    include <newton/algorithm/algorithm.hpp>
    
    if ( newton::exists_linear(first, last, value) )
       do_this();
    else
       do_that();
    
  • 1

    如果您的矢量未订购,请使用MSN建议的方法:

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

    如果您的矢量是有序的,请使用binary_search方法Brian Neal建议:

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

    二进制搜索产生O(log n)最坏情况性能,这比第一种方法更有效 . 为了使用二进制搜索,您可以使用qsort对向量进行排序,以保证它是有序的 .

  • 8

    你可以试试这段代码:

    #include <algorithm>
    #include <vector>
    
    // You can use class, struct or primitive data type for Item
    struct Item {
        //Some fields
    };
    typedef std::vector<Item> ItemVector;
    typedef ItemVector::iterator ItemIterator;
    //...
    ItemVector vtItem;
    //... (init data for vtItem)
    Item itemToFind;
    //...
    
    ItemIterator itemItr;
    itemItr = std::find(vtItem.begin(), vtItem.end(), itemToFind);
    if (itemItr != vtItem.end()) {
        // Item found
        // doThis()
    }
    else {
        // Item not found
        // doThat()
    }
    
  • 2

    使用C运算符的另一个示例

    #include <vector>
    #include <algorithm>
    #include <stdexcept>
    
    template<typename T>
    inline static bool operator ==(const std::vector<T>& v, const T& elem)
    {
      return (std::find(v.begin(), v.end(), elem) != v.end());
    }
    
    template<typename T>
    inline static bool operator !=(const std::vector<T>& v, const T& elem)
    {
      return (std::find(v.begin(), v.end(), elem) == v.end());
    }
    
    enum CODEC_ID {
      CODEC_ID_AAC,
      CODEC_ID_AC3,
      CODEC_ID_H262,
      CODEC_ID_H263,
      CODEC_ID_H264,
      CODEC_ID_H265,
      CODEC_ID_MAX
    };
    
    void main()
    {
      CODEC_ID codec = CODEC_ID_H264;
      std::vector<CODEC_ID> codec_list;
    
      codec_list.reserve(CODEC_ID_MAX);
      codec_list.push_back(CODEC_ID_AAC);
      codec_list.push_back(CODEC_ID_AC3);
      codec_list.push_back(CODEC_ID_H262);
      codec_list.push_back(CODEC_ID_H263);
      codec_list.push_back(CODEC_ID_H264);
      codec_list.push_back(CODEC_ID_H265);
    
      if (codec_list != codec)
      {
        throw std::runtime_error("codec not found!");
      }
    
      if (codec_list == codec)
      {
        throw std::logic_error("codec has been found!");
      }
    }
    
  • 788

    这是一个适用于任何Container的函数:

    template <class Container> 
    const bool contains(const Container& container, const typename Container::value_type& element) 
    {
        return std::find(container.begin(), container.end(), element) != container.end();
    }
    

    请注意,您可以使用1个模板参数,因为您可以从Container中提取 value_type . 你需要 typename 因为 Container::value_typedependent name .

  • 45

    您可以使用std::find std::find

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

    这将返回一个bool( true 如果存在,否则为 false ) . 用你的例子:

    #include <algorithm>
    
    if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
       do_this();
    else
       do_that();
    
  • 3

    使用STL find功能 .

    请记住,还有一个find_if函数,如果您的搜索更复杂,可以使用它,例如,如果您不只是查找元素,但是,例如,想要查看是否存在满足某个元素的元素condition,例如,以"abc"开头的字符串 . ( find_if 会给你一个指向第一个这样的元素的迭代器) .

  • 9

    你也可以使用伯爵 . 它将返回向量中存在的项目数 .

    int t=count(vec.begin(),vec.end(),item);
    
  • 8
    template <typename T> bool IsInVector(T what, std::vector<T> * vec)
    {
        if(std::find(vec->begin(),vec->end(),what)!=vec->end())
            return true;
        return false;
    }
    
  • 100

    我用这样的东西......

    #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
    

    ......就这样,它实际上清晰可读 . (显然,您可以在多个位置重复使用模板) .

  • -1

    您可以使用 std 命名空间中的find函数,即 std::find . 您从要搜索的向量中传递 std::findend 迭代器的 std::find 函数以及您要查找的元素,并将得到的迭代器与向量的末尾进行比较,以查看它们是否匹配 .

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

    您还可以解除引用迭代器并像往常一样使用它,就像任何其他迭代器一样 .

相关问题