user4979733 user4979733 - 1 month ago 14
C++ Question

C++: Find any element from container1 not in container2

I have a

std::set<int>
(s) and a
std::vector<int>
(v). The vector is guaranteed to be sorted/unique. I want to know if all elements of v are in s (or just stop at the first element of v not in s). I could convert v into a set and do == test, but is there another way without changing the container type?

Answer

What's about std::includes algorithm?

Here's a short usage example:

vector<int> v1 { 1, 2, 4, 8 };
vector<int> v2 { 1, 2, 3, 8 };
set<int> s { 0, 1, 2, 4, 8, 16 };
cout << includes(s.begin(), s.end(), v1.begin(), v1.end()) << endl;
cout << includes(s.begin(), s.end(), v2.begin(), v2.end()) << endl;

Output:

1
0
Comments