Here is a solution which works on the keys by defining a new key_iterator
, which returns the key elements only. The solution is inspirde by this post.
#include <iostream>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
typedef std::map<int,std::string> MapType;
typedef MapType::iterator IteratorType;
struct key_iterator : public IteratorType
{
key_iterator() : IteratorType() {}
key_iterator(IteratorType it) : IteratorType(it) {}
int* operator->() {return (int* const)& IteratorType::operator->()->first;}
int operator*() {return IteratorType::operator*().first;}
};
int main() {
std::map<int,std::string> m1;
m1[3]="1 2 4";
m1[6]="3 4 6";
std::map<int,std::string> m2;
m2[3]="3 5 6";
m2[6]="6 4 8";
m2[8]="2 4 3";
m2[10]="2 5 7 9";
std::vector<int> v;
key_iterator it1_begin=m1.begin();
key_iterator it1_end=m1.end();
key_iterator it2_begin=m2.begin();
key_iterator it2_end=m2.end();
std::set_difference(it2_begin, it2_end, it1_begin, it1_end, std::inserter(v,v.begin()));
for(auto i : v)
std::cout<<i<<" ";
std::cout<<std::endl;
// your code goes here
return 0;
}
This code prints
8 10
Live example.
If someone comes up with a nicer syntax for invoking std::set_difference
, go ahead.