Datenstrukturen in c++: Map/Dictionary

avatar

Eine Map ("Karte", eher Abbildung) auch Hashtable oder Dictionary genannt ist eine Datenstruktur die einem Schlüssel (key) einen Schlüsselwert (value) zuordnet. Die Schlüssel sind frei von Duplikate und die Schlüsselwerte lassen sich mit dem zugehörigen Schlüssel ansprechen. Auch die Maps haben keine Indizes, allerdings lassen sich Maps, genauso wie Sets, mithilfe von Iteratoren durchlaufen.

Die Theorie hinter dem key/value-Pair einer Map: https://peakd.com/hive-196387/@ozelot47/datenstrukturen-hashmap-hashtabelle

#include <iostream>
#include <map>

void map(){
    /* a map required two specified datatypes */
    /* the first is the key and the second is a value */
    std::map<int, std::string> container;

    /* insert a pair into a map */
    container.insert(std::pair<int,std::string>(1,"Eins"));
    container.insert(std::pair<int,std::string>(2,"Zwei"));

    /* or you can also do it like... */
    container[3] = "Drei";
    container[4] = "Vier";

    /* delete a key. Be careful! It's value will also be deleted! */
    container.erase(3);

    /* get a value from a key */
    auto it = container.find(2);
    if( it != container.end()){
        std::cout << it->second << "\n";
    } else {
        std::cout << "no value because the key doesn't exist" << "\n";
    }

    /* print the entire map */
    /* first is the key, second is the value */
    for(auto& entry : container){
        std::cout << entry.first << " " << entry.second << "\n";
    }
}

int main(){
    map();
    return 0;
}


0
0
0.000
0 comments