Reputation: 27581
Given two vectors of integers, how to determinate if there's some element from 1st vector is present in 2nd one?
Upvotes: 0
Views: 695
Reputation: 347216
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.
Upvotes: 4
Reputation: 1394
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);
Upvotes: 0
Reputation: 6476
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";
Upvotes: 9