如何找出std :: vector中是否存在项目?

我要作的就是检查向量中是否存在某个元素,所以我能够处理每种状况。 性能

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

#1楼

您能够尝试如下代码: this

#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楼

若是没有订购您的向量,请使用建议的MSN方法: spa

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

若是您的向量是有序的,请使用binary_search方法Brian Neal建议: code

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

二进制搜索产生O(log n)最坏状况的性能,比第一种方法更有效。 为了使用二进制搜索,您可使用qsort首先对向量进行排序以确保其排序。 排序


#3楼

若是您想在向量中找到一个字符串: 字符串

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));

#4楼

我用这样的东西... string

#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

...那样其实是清晰易读的。 (显然,您能够在多个地方重复使用模板)。 it


#5楼

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;
}
相关文章
相关标签/搜索