tags:

views:

143

answers:

3

Given two vectors of integers, how to determinate if there's some element from 1st vector is present in 2nd one?

+4  A: 

You could take the set_intersection of both vectors, and then check if the resulting intersection is empty:

std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::set_intersection(v1.begin()
  , v1.end()
  , v2.begin()
  , v2.end()
  , std::back_inserter(v3));
bool containsElements = !v3.empty();

set_intersection can be found in #include <algorithm>

For set_intersection to work, both vectors must first be sorted.

Brian R. Bondy
It's worth noting that v1 and v2 must be sorted for this to work.
Charles Bailey
It's worth noting that you should prefer `v3.empty()` to `v3.size() == 0`.
Matthieu M.
@Charles Bailey and @Matthie M.: I added both of these, thanks.
Brian R. Bondy
+9  A: 

I guess something like this should work:

std::vector<int> v1,v2;
if(std::find_first_of(v2.begin(),v2.end(),v1.begin(),v1.end()) != v2.end())
   std::cout << "found!\n";
catwalk
this is exactly what I'm looking for
dimba
Although it may appear worse in complexity `O(v1.size() * v2.size())`, it doesn't really matter on small sets, and you don't have to modify (sort) your vectors beforehand.
Matthieu M.
A: 

I think something like this:

bool contains(const std::vector<int>& vec, int val){
    for(std::vector<int>::const_iterator it=vec.begin(); it!=vec.end(); ++it){
        if(*it==val){
            return true;
        }
    }
    return false;
}

bool contains(const std::vector<int>& from, const std::vector<int>& in){
    for(std::vector<int>::const_iterator it=from.begin(); it!=from.end(); ++it){
        if(contains(in, *it)){
            return true;
        }
    }
    return false;
}

// Example
std::vector<int> a;
std::vector<int> b;

a.push_back(2);
a.push_back(1);
b.push_back(0);
b.push_back(1);

bool contains = contains(a, b);
VDVLeon
this is equal to handwritten for in for. I' looking for a STL way solution
dimba
I did read your for in for opinion after i post it :P
VDVLeon