More Maps
More on Maps
#include <iostream>
#include <vector>
#include <unordered_map> //c++11
#include <map>
using namespace std;
int main()
{
// key value
unordered_map < string, int > na;
//map < string, int > na;
na["bob"] = 23; // add key/value pairs
na["sarah"]= 21;
na["bob"] = 5; //overwrite
na["bill"] = 8;
na["adam"]= 200;
na["zion"]= 3;
na["cathy"]=55;
na.erase("sarah");
//three ways to iterate
//
//1
//map<string,int>::const_iterator i;
//for (i=na.begin(); i!=na.end(); i++)
for (auto i=na.begin(); i!=na.end(); i++)
cout<< i->first << ": " << i->second << endl;
// key value
cout<<endl;
/*
//if container is a map (not unordered_map)
//we can iterate backwards
for (auto i=na.rbegin(); i!=na.rend(); i++)
cout<< i->first << ": " << i->second << endl;
*/
cout<<endl;
na["sarah"]=11;
//2
//c++11
for (auto x: na) //auto &x and auto const &x
{
cout << x.first<< ": "<< x.second << endl;
if (x.first=="sarah")
na["sarah"]=22;
}
cout<<endl;
/*
//3
//c++17
for (auto [k, v]: na )
cout << k << ": " << v <<endl;
*/
//cout<<na["bill"]<<endl; //returns value 0 but also adds bill,0 to map (na["bill]=0)
//cout<<na.at("bill")<<endl; //fails
//does key bob exist
if (na.find("bill") != na.end())
{
cout << "found bill "<<na["bill"] << endl;
}
else
{
cout<< "bill is not a key in the map"<<endl;
}
//alternate find
//if we need to store iterator location to access pair
unordered_map<string, int>::iterator p;
//map<string, int>::iterator p;
if ((p=na.find("sarah"))!=na.end())
{
cout<< "found "<< p->first <<" "<< p->second <<endl;
}
//second alternate find with easier syntax
auto q=na.find("sarah");
if (q != na.end())
{
cout<< "found "<< q->first <<" "<< q->second <<endl;
}
return 0;
}