Map

Mengenoperationen auf maps

Die Frage lautet: Wie verheiratet man map und set_intersection(), damit man die Schnittmenge der Maps bekommt?

,
/*
  map with set_intersection example
  Christoph Becker 2008
 
  g++ set_intersection.cc -o set_intersection
*/
#include <iostream> // cout
#include <iterator>
#include <map>
#include <string>
 
using namespace std;
 
 
typedef map<string, int> hostlist;
typedef hostlist::iterator iter;
 
void showMap(hostlist newList, string name)
{
    iter it;
    cout << endl << name << ":\n";
    for ( it = newList.begin() ; it != newList.end(); it++ )
    {
        cout << " * "
            << (*it).first << " => " << (*it).second
            <<  endl;
    }
}
 
void contains(hostlist outer, hostlist inner, string oname, string iname)
{
    string cont;
    // whats included aka Teilmenge
    if (includes(outer.begin(), outer.end(), inner.begin(), inner.end()))
    {
        cont = "contains";
    }
    else
    {
        cont = "does not contain";
    }
 
    cout << oname <<" list " << cont << " " << iname <<" list" << endl;
}
 
int main() {
    hostlist newList, oldList, smallList, dstList;
 
    // fill
    newList["10.3.0.1"] = 1000;
    newList["10.3.0.2"] = 2000;
    newList["10.3.0.3"] = 3000;
 
    oldList["10.3.0.1"] = 1000;
    oldList["10.3.0.2"] = 4000;
    oldList["10.3.0.3"] = 4000;
 
    smallList["10.3.0.3"] = 3000;
 
    showMap(newList, "new list");
    showMap(oldList, "old list");
    showMap(smallList, "small list");
 
 
    // intersection aka Schnittmenge
    set_intersection(newList.begin(), newList.end(),
                    oldList.begin(), oldList.end(),
                    inserter(dstList, dstList.begin()) );
    showMap(dstList, "intersection");
 
    dstList.clear();
    // whats different aka Differenzmenge
    set_difference(newList.begin(), newList.end(),
                    oldList.begin(), oldList.end(),
                    inserter(dstList, dstList.begin()) );
    showMap(dstList, "difference");
 
    dstList.clear();
    // union aka Vereinigungsmenge
    set_union(newList.begin(), newList.end(),
                    oldList.begin(), oldList.end(),
                    inserter(dstList, dstList.begin()) );
    showMap(dstList, "union");
 
    // whats included aka Teilmenge
    cout << endl;
    contains(newList, oldList, "new", "old");
    contains(newList, smallList, "new", "small" );
    contains(oldList, smallList, "old", "small");
}
public/cpp/map.txt · Zuletzt geändert: 2009/04/24 20:39 (Externe Bearbeitung)
chimeric.de = chi`s home Creative Commons License Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0