Using a map with set_intersection
Posted
by Robin Welch
on Stack Overflow
See other posts from Stack Overflow
or by Robin Welch
Published on 2010-04-13T23:53:54Z
Indexed on
2010/04/14
0:02 UTC
Read the original article
Hit count: 285
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[1] ) );
map1.insert( MoneyPair( 2, mn[2] ) );
map1.insert( MoneyPair( 3, mn[3] ) ); // (3)
map1.insert( MoneyPair( 4, mn[4] ) ); // (4)
MoneyMap map2;
map1.insert( MoneyPair( 3, mn[3] ) ); // (3)
map1.insert( MoneyPair( 4, mn[4] ) ); // (4)
map1.insert( MoneyPair( 5, mn[5] ) );
map1.insert( MoneyPair( 6, mn[6] ) );
map1.insert( MoneyPair( 7, mn[7] ) );
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.
© Stack Overflow or respective owner