Not used set_intersection before, but I believe it will work with maps. I wrote the following example code but it doesn't give me what I'd expect:
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
struct Money
{
double amount;
string currency;
bool operator< ( const Money& rhs ) const
{
if ( amount != rhs.amount )
return ( amount < rhs.amount );
return ( currency < rhs.currency );
}
};
int main( int argc, char* argv[] )
{
Money mn[] =
{
{ 2.32, "USD" },
{ 2.76, "USD" },
{ 4.30, "GBP" },
{ 1.21, "GBP" },
{ 1.37, "GBP" },
{ 6.74, "GBP" },
{ 2.55, "EUR" }
};
typedef pair< int, Money > MoneyPair;
typedef map< int, Money > MoneyMap;
MoneyMap map1;
map1.insert( MoneyPair( 1, mn[0] ) );
map1.insert( MoneyPair( 2, mn[1] ) );
map1.insert( MoneyPair( 3, mn[2] ) ); // (3)
map1.insert( MoneyPair( 4, mn[3] ) ); // (4)
MoneyMap map2;
map2.insert( MoneyPair( 3, mn[2] ) ); // (3)
map2.insert( MoneyPair( 4, mn[3] ) ); // (4)
map2.insert( MoneyPair( 5, mn[4] ) );
map2.insert( MoneyPair( 6, mn[5] ) );
map2.insert( MoneyPair( 7, mn[6] ) );
MoneyMap out;
MoneyMap::iterator out_itr( out.begin() );
set_intersection( map1.begin(), map1.end(), map2.begin(), map2.end(), inserter( out, out_itr ) );
cout << "intersection has " << out.size() << " elements." << endl;
return 0;
}
Since the pair labelled (3) and (4) appear in both maps, I was expecting that I'd get 2 elements in the intersection, but no, I get:
intersection has 0 elements.
I'm sure this is something to do with the comparitor on the map / pair but can't figure it out.