Reputation: 21
I have declared two maps m1
and m2
.
Map m1's keys are in the keys of m2. But all the keys of m2 are not in the keys of m1.
Can anyone help me how to find the uncommon keys in m2 compared to the keys of m1?
Example
m1 contains:
3=> 1 2 4
6=> 3 4 6
m2 contains:
3 => 3 5 6
6 => 6 4 8
8 => 2 4 3
10 => 2 5 7 9
The output would be 8 and 10.
Upvotes: 1
Views: 402
Reputation: 15478
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
If someone comes up with a nicer syntax for invoking std::set_difference
, go ahead.
Upvotes: 1
Reputation: 172924
You can do it by std::set_difference. Example:
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::map<int, std::string> m3;
std::set_difference(m2.begin(), m2.end(), m1.begin(), m1.end(), std::inserter(m3, m3.begin()), m1.value_comp());
for (auto i = m3.begin(); i != m3.end(); ++i) {
std::cout << "[" << i->first << "," << i->second << "]";
}
std::cout << std::endl;
Result:
[8,2 4 3][10,2 5 7 9]
Upvotes: 3
Reputation: 88378
You didn't specify a programming language, so here's some pseudocode:
m2.keySet() - m1.keySet()
Languages like Python have a -
operator that works on sets, so the above is all that is needed.
Here is some actual Python code:
>>> m1 = {'x':4, 'y':3}
>>> m2 = {'x':4, 'y':3, 'z':5}
>>> set(m2.keys())-set(m1.keys())
set(['z'])
Upvotes: 0