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?
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
I think you are looking for std::set::count
or std::unordered_set::count
:
if( v.size() > s.size() )
{
// since v has unique values
// v is not subset of s
// if you need to find a first element of v not in s
// you need to run the loop below anyway
}
for( auto i : v )
{
if( !s.count( i ))
{
// i not in s
}
}
If you need all elements of v not in s, just use std::set_difference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With