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

发布于 2025-01-25 20:50:11 字数 118 浏览 3 评论 0 原文

我要做的就是检查矢量中是否存在一个元素,以便我可以处理每种情况。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

月竹挽风 2025-02-01 20:50:11

您可以使用 std :: find ><算法> :

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

这将返回到第一个元素。如果不存在,它会将迭代器返回到持久的一半。与您的示例:

#include <algorithm>
#include <vector>

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

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

#include <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 an iterator to the first element found. If not present, it returns an iterator to one-past-the-last. With your example:

#include <algorithm>
#include <vector>

if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
   do_this();
else
   do_that();
悲念泪 2025-02-01 20:50:11

正如其他人所说,使用stl find_if functions。但是,如果您要在非常大的向量中搜索并影响性能,则可能需要对矢量进行分类,然后使用 binary_search 算法。

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.

任谁 2025-02-01 20:50:11

如果未订购您的向量,请使用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首先对矢量进行排序,以确保其订购。

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.

梅倚清风 2025-02-01 20:50:11

使用从Stl的算法标题中查找。我已经说明了其与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;
}

Use find from the algorithm header of stl.I've illustrated its use with int type. You can use any type you like as long as you can compare for equality (overload == if you need to for your custom class).

#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;
}
睡美人的小仙女 2025-02-01 20:50:11

在C ++ 11中,您可以使用 any_of 。例如,如果是 vector&lt; string&gt; v; 然后:

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

或者使用lambda:

if (any_of(v.begin(), v.end(), [&](const std::string& elem) { return elem == item; }))
   do_this();
else
   do_that();

In C++11 you can use any_of. For example if it is a vector<string> v; then:

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

Alternatively, use a lambda:

if (any_of(v.begin(), v.end(), [&](const std::string& elem) { return elem == item; }))
   do_this();
else
   do_that();
熊抱啵儿 2025-02-01 20:50:11

在C ++ 23中,我们终于有一个体面的解决方案

if (std::ranges::contains(vec, item))
   do_this();
else
   do_that();

In C++23 we finally have a decent solution:

if (std::ranges::contains(vec, item))
   do_this();
else
   do_that();
jJeQQOZ5 2025-02-01 20:50:11

我使用这样的东西...

#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

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

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

放飞的风筝 2025-02-01 20:50:11

从C ++ 20,使用范围( #include&lt; ranges&gt;

    //SAMPLE DATA
    std::vector<int> vecOfElements = { 2,4,6,8 };

    //DO SOMETHING IF 8 IN VECTOR
    if (std::ranges::find(vecOfElements, 8) != vecOfElements.end())
    {
        std::cout << "DO SOMETHING" << std::endl;
    }

From C++20, using ranges (#include <ranges>)

    //SAMPLE DATA
    std::vector<int> vecOfElements = { 2,4,6,8 };

    //DO SOMETHING IF 8 IN VECTOR
    if (std::ranges::find(vecOfElements, 8) != vecOfElements.end())
    {
        std::cout << "DO SOMETHING" << std::endl;
    }
唠甜嗑 2025-02-01 20:50:11

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

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个模板参数逃脱,因为您可以从容器中提取 value_type 。您需要 typename 因为容器:: value_type 依赖性名称

Here's a function that will work for any 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();
}

Note that you can get away with 1 template parameter because you can extract the value_type from the Container. You need the typename because Container::value_type is a dependent name.

故事↓在人 2025-02-01 20:50:11

请记住,如果您要进行很多查找,那么有一些STL容器会更好。我不知道您的应用程序是什么,但是像STD :: MAP这样的关联容器可能值得考虑。

std :: vector是选择的容器,除非您有另一个原因,而按值进行查找可能就是这样的原因。

Bear in mind that, if you're going to be doing a lot of lookups, there are STL containers that are better for that. I don't know what your application is, but associative containers like std::map may be worth considering.

std::vector is the container of choice unless you have a reason for another, and lookups by value can be such a reason.

半窗疏影 2025-02-01 20:50:11

使用Boost,您可以使用 any_of_equal

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

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

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);
千鲤 2025-02-01 20:50:11

使用stl 查找函数。

请记住,还有一个 find_if 函数,如果您可以使用,如果您可以使用它们搜索更为复杂,即如果您不仅在寻找元素,例如,是否要查看是否有一个元素满足特定条件,例如,以“ ABC”开头的字符串。 ( find_if 将为您提供指向第一个此类元素的迭代器)。

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

通知家属抬走 2025-02-01 20:50:11

您可以尝试此代码:

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

You can try this code:

#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()
}
云之铃。 2025-02-01 20:50:11

您可以使用 查找 代码> std 名称空间,即 std ::查找。您通过 std :: find 函数开始 end 从您要搜索的向量以及您正在查找的元素中读取器因为并将结果迭代器与向量的末端进行比较,以查看它们是否匹配。

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

您还能够像其他任何迭代器一样放弃迭代器并正常使用它。

You can use the find function, found in the std namespace, ie std::find. You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.

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

You're also able to dereference that iterator and use it as normal, like any other iterator.

落花浅忆 2025-02-01 20:50:11

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

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

You can use count too.
It will return the number of items present in a vector.

int t=count(vec.begin(),vec.end(),item);
征棹 2025-02-01 20:50:11

我亲自使用了最近的模板来一次处理多种类型的容器,而不仅仅是处理矢量。我在网上找到了一个类似的例子(不记得在哪里),所以无论我从中窃取了这一点,都将获得信用。这种特殊的模式似乎也处理了原始阵列。

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

I've personally used templates of late to handle multiple types of containers at once rather than deal only with vectors. I found a similar example online (can't remember where) so credit goes to whoever I've pilfered this from. This particular pattern seems to handle raw arrays as well.

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);
}
小梨窩很甜 2025-02-01 20:50:11
template <typename T> bool IsInVector(const T & what, const std::vector<T> & vec)
{
    return std::find(vec.begin(),vec.end(),what)!=vec.end();
}
template <typename T> bool IsInVector(const T & what, const std::vector<T> & vec)
{
    return std::find(vec.begin(),vec.end(),what)!=vec.end();
}
再浓的妆也掩不了殇 2025-02-01 20:50:11

(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/algorithm/searchm/search

(C++17 and above):

can use std::search also

This is also useful for searching sequence of elements.

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

Also there is flexibility of passing some search algorithms. Refer here.

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

坚持沉默 2025-02-01 20:50:11

如果您想在向量中找到字符串:

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

If you wanna find a string in a vector:

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));
放肆 2025-02-01 20:50:11

另一种方法是使用 std :: count

示例代码:

#include <algorithm>
#include <vector>

void run_vector_contains_example() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    int item_to_find = 3;

    int count = std::count(vec.begin(), vec.end(), item_to_find);

    if (count > 0) {
        // item found in vector
    } else {
        // item not found in vector
    }
}

诚然,此方法可能比 std ::与大型矢量打交道时

Another way to do it is using std::count.

Example code:

#include <algorithm>
#include <vector>

void run_vector_contains_example() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    int item_to_find = 3;

    int count = std::count(vec.begin(), vec.end(), item_to_find);

    if (count > 0) {
        // item found in vector
    } else {
        // item not found in vector
    }
}

Admittedly, this method might be slower than std::find when dealing with large vectors.

南巷近海 2025-02-01 20:50:11

怎么样?

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

int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};

// Find element 3 in the vector
auto it = std::find(vec.begin(), vec.end(), 3);

// Check if element is found
if (it != vec.end()) {
    // Calculate index of the found element
    int index = std::distance(vec.begin(), it);
    std::cout << "Element 3 found at index: " << index << std::endl;
} else {
    std::cout << "Element 3 not found" << std::endl;
}

return 0;
}

How about this way?

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

int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};

// Find element 3 in the vector
auto it = std::find(vec.begin(), vec.end(), 3);

// Check if element is found
if (it != vec.end()) {
    // Calculate index of the found element
    int index = std::distance(vec.begin(), it);
    std::cout << "Element 3 found at index: " << index << std::endl;
} else {
    std::cout << "Element 3 not found" << std::endl;
}

return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文