Check if element is in the list (contains)

2019-03-09 08:57发布

I've got a list of elements, say, integers and I want to check if my variable (another integer) is one of the elements from the list. In python I'd do:

my_list = [1,2,3,4] # elements
my_var = 3 # my variable
my_var in my_list # returns boolean

How to do that in C++? I thought of using std::list, but I can find no find method in it. I can see such method in std::set structure.

More deeply, the problem is that my program is given some unique ids (a list, a set, whatever) and I iterate over a long list of input data (ids) and check if they are included in the list (boolean value returned for each iteration step). And I'm not sure how should I do that in C++.

标签: c++ contains
6条回答
贪生不怕死
2楼-- · 2019-03-09 09:12

Use std::find, something like:

if (std::find(std::begin(my_list), std::end(my_list), my_var) != std::end(my_list))
    // my_list has my_var
查看更多
地球回转人心会变
3楼-- · 2019-03-09 09:21

Declare additional helper function like this:

template <class T, class I >
bool vectorContains(const vector<T>& v, I& t)
{
    bool found = (std::find(v.begin(), v.end(), t) != v.end());
    return found;
}

And use it like this:

void Project::AddPlatform(const char* platform)
{
    if (!vectorContains(platforms, platform))
        platforms.push_back(platform);
}

Snapshot of example can be found here:

https://github.com/tapika/cppscriptcore/blob/b7f3d62747494a52a440482e841ffb016a3fc56e/SolutionProjectModel/Project.cpp#L13

查看更多
叼着烟拽天下
4楼-- · 2019-03-09 09:31

They really should add a wrapper. Like this:

namespace std
{
    template<class _container,
        class _Ty> inline
        bool contains(_container _C, const _Ty& _Val)
        {return std::find(_C.begin(), _C.end(), _Val) != _C.end(); }
};
...
    if( std::contains(my_container, what_to_find) )
    {

    }
查看更多
混吃等死
5楼-- · 2019-03-09 09:33

std::list does not provide a search method. You can iterate over the list and check if the element exists or use std::find. But I think for your situation std::set is more preferable. The former will take O(n) time but later will take O(lg(n)) time to search.

You can simply use:

if(mySet.find(myVar) != mySet.end()){
      //do whatever
}
查看更多
再贱就再见
6楼-- · 2019-03-09 09:33

you must #include <algorithm>, then you can use std::find

查看更多
做个烂人
7楼-- · 2019-03-09 09:34

You can use std::find

bool found = (std::find(my_list.begin(), my_list.end(), my_var) != my_list.end());

You need to include <algorithm>. It should work on standard containers, vectors lists, etc...

查看更多
登录 后发表回答