Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 903
user4979733 Avatar asked Jun 01 '16 22:06

user4979733


2 Answers

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
like image 127
Edgar Rokjān Avatar answered Sep 22 '22 09:09

Edgar Rokjān


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

like image 29
lllllllllll Avatar answered Sep 24 '22 09:09

lllllllllll