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
2009-12-10 18:04:06
It's worth noting that v1 and v2 must be sorted for this to work.
Charles Bailey
2009-12-10 18:11:33
It's worth noting that you should prefer `v3.empty()` to `v3.size() == 0`.
Matthieu M.
2009-12-10 18:19:12
@Charles Bailey and @Matthie M.: I added both of these, thanks.
Brian R. Bondy
2009-12-11 00:40:21
+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
2009-12-10 18:06:45
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.
2009-12-10 18:21:54
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
2009-12-10 18:08:50