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

时间:2009-02-20 21:58:42

标签: c++ vector std

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

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

19 个答案:

答案 0 :(得分:841)

您可以使用<algorithm>中的std::find

#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()

这会返回一个bool(true如果存在,否则为false)。举个例子:

#include <algorithm>
#include <vector>

if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
   do_this();
else
   do_that();

答案 1 :(得分:104)

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

答案 2 :(得分:46)

使用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;
}

答案 3 :(得分:36)

如果您的矢量未订购,请使用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对向量进行排序,以保证它是有序的。

答案 4 :(得分:19)

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

#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

......就这样,它实际上清晰可读。 (显然你可以在多个地方重复使用模板)。

答案 5 :(得分:11)

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

$this

请注意,您可以使用1个模板参数,因为您可以从Container中提取$object。您需要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(); } ,因为value_typedependent name

答案 6 :(得分:10)

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

std :: vector是您选择的容器,除非您有其他的理由,并且按值查找可能是这样的原因。

答案 7 :(得分:10)

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

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

答案 8 :(得分:8)

使用STL find功能。

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

答案 9 :(得分:7)

使用提升功能,您可以使用any_of_equal

#include <boost/algorithm/cxx11/any_of.hpp>

bool item_present = boost::algorithm::any_of_equal(vector, element);

答案 10 :(得分:5)

您可以尝试以下代码:

#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()
}

答案 11 :(得分:3)

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

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

您也可以像其他任何迭代器一样解除对迭代器的解除引用并正常使用它。

答案 12 :(得分:3)

您也可以使用计数。 它将返回向量中存在的项目数。

int t=count(vec.begin(),vec.end(),item);

答案 13 :(得分:2)

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

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

答案 14 :(得分: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!");
  }
}

答案 15 :(得分:1)

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

答案 16 :(得分:0)

(C ++ 17及更高版本):

也可以使用std::search

这对于搜索元素序列也很有用。

#include <algorithm>
#include <iostream>
#include <vector>

template <typename Container>
bool search_vector(const Container& vec, const Container& searchvec)
{
    return std::search(vec.begin(), vec.end(), searchvec.begin(), searchvec.end()) != vec.end();
}

int main()
{
     std::vector<int> v = {2,4,6,8};

     //THIS WORKS. SEARCHING ONLY ONE ELEMENT.
     std::vector<int> searchVector1 = {2};
     if(search_vector(v,searchVector1))
         std::cout<<"searchVector1 found"<<std::endl;
     else
         std::cout<<"searchVector1 not found"<<std::endl;

     //THIS WORKS, AS THE ELEMENTS ARE SEQUENTIAL.
     std::vector<int> searchVector2 = {6,8};
     if(search_vector(v,searchVector2))
         std::cout<<"searchVector2 found"<<std::endl;
     else
         std::cout<<"searchVector2 not found"<<std::endl;

     //THIS WILL NOT WORK, AS THE ELEMENTS ARE NOT SEQUENTIAL.
     std::vector<int> searchVector3 = {8,6};
     if(search_vector(v,searchVector3))
         std::cout<<"searchVector3 found"<<std::endl;
     else
         std::cout<<"searchVector3 not found"<<std::endl;
}

通过某些搜索算法也很灵活。请参阅此处。

https://en.cppreference.com/w/cpp/algorithm/search

答案 17 :(得分:0)

我最近个人使用模板来一次处理多种类型的容器,而不仅仅是处理向量。我在网上找到了一个类似的示例(不记得在哪里),因此,无论我从哪里窃取此信息,都应归功于它。这种特殊的模式似乎也可以处理原始数组。

template <typename Container, typename T = typename std::decay<decltype(*std::begin(std::declval<Container>()))>::type>
bool contains(Container && c, T v)
{
    return std::find(std::begin(c), std::end(c), v) != std::end(c);
}

答案 18 :(得分:-1)

使用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();
相关问题