Maps

Maps

Note: Map iterators

I made a mistake in the video.

vector and string use random access iterators. So < is valid BUT map uses bidirectional iterators. unordered_map uses forward iterators.

#include <iostream>
#include <vector>
#include <unordered_map> //c++11
using namespace std;

int main(){
    //              key     value
    unordered_map < string, int >  nameage;
    nameage["bob"] = 23; // add key/value pairs
    nameage["sarah"]= 21;
    nameage["bob"] = 5; //overwrite
    //nameage["bill"] = 8; 
    nameage.erase("sarah");
    //three ways to iterate
    //
    //1
    //map<string,int>::iterator i;
    //for (i=nameage.begin(); i!=nameage.end(); i++)
    for (auto i=nameage.begin(); i!=nameage.end(); i++) //cannot use <
        cout<< i->first << ": " << i->second << endl;
    //        key                 value

    //2
    //c++11
    for (auto x: nameage)
        cout << x.first<< ": "<< x.second << endl;


    //3
    //c++17 use g++ -std=c++17 
    for (auto [k, v]: nameage )
        cout << k << ": " << v <<endl;

    //cout<<nameage["bill"]<<endl; //returns value 0 but also adds bill,0 to map 
    //cout<<nameage.at("bill")<<endl; //fails. Does not add default values

    //does key exist
    if (nameage.find("bill") != nameage.end())
    {
                cout << nameage["bill"] << endl;
    }
    else
    {
        cout<< "bill is not a  key in the map"<<endl;
    }

    return 0;
}