Search code examples
c++dictionarysetset-difference

Find set_difference between set and map keys


I would like to ask if it is possible to provide an example on how I can find the difference between a set and keys of a map using set_difference

I know that another question std::set_difference is it possible to compare set and map Keys? but it points to another question without a clear example. I need a solution without using boost library

#include <algorithm>
#include <set>
#include <iterator>
// ...
std::set<int> s1, s2;
// Fill in s1 and s2 with values
std::set<int> result;
std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
    std::inserter(result, result.end()));

Solution

  • You can do it with a custom comparator. Standard algorithms use strict weak ordering. To test for equality of two elements, the comparator needs to be aplied twice. Two elements are equal when both comp(first, second) and comp(second, first) return false (where comp is the comparator function). Since the elements you want to compare are of different types, one comparator won't do - you'll need two overloads:

    struct cmp {
        bool operator()(int i, const std::pair<int, double>& p) const
        {
            return i < p.first;
        }
    
        bool operator()(const std::pair<int, double>& p, int i) const
        {
            return p.first < i;
        }
    
    };
    
    int main()
    {
    
        std::set<int> s1 { 1, 2, 3, 4 };
        std::map<int, double> s2 { {1, 0}, {2,0}, {4,0} };
    
        std::set<int> result;
    
        std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
            std::inserter(result, result.end()), cmp());
    
        std::cout << *result.begin(); // will print 3
    
    }