Thursday, 12 March 2009

An example of C++ maps

The following example shows the working of C++ maps. This also has a simple example of union which is sometimes used in C and C++ programs


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows an example of how maps work.
//In maps, the first parameter is key and second value
//The keys in the map are automatically softed from lower to higher
#include<iostream>
#include<map>
#include<string>

using namespace
std;

//defining a union that is used with newMap_
union uu
{

char
c;
int
i;
}
u;

//Lets define two different maps
//The first parameter is key and second value
map<string, int> portMap_;
map<void *, uu> newMap_;

int
main()
{

//first entry in portmap
portMap_["first"] = 1;

//example of using the iterator
map<string, int>::const_iterator it;
string z = "second";
it = portMap_.find(z); //not in the map so wont be found
if(it == portMap_.end())
{

portMap_[z] = 22; //add second element
}

//Add thrid element directly
z = "third";
portMap_[z] = 12345;

//Add 4th element by insert
portMap_.insert(pair<string,int>("fourth", 4444));

//Add 5th element by insert
portMap_.insert(pair<string,int>("fifth", 5555));


cout<<"\n** Printing the portmap_ values **"<<endl;
for
(it = portMap_.begin(); it != portMap_.end(); ++it)
cout<<"Key = "<<it->first<<" Val = "<<it->second<<endl;

cout<<"\n** Removing fourth element **"<<endl;
z = "fourth";
it = portMap_.find(z);
portMap_.erase(it);

cout<<"\n** Printing the portmap_ values **"<<endl;
for
(it = portMap_.begin(); it != portMap_.end(); ++it)
cout<<"Key = "<<it->first<<" Val = "<<it->second<<endl;

//Playing with New Map
cout<<"\n\nCreating New Map whose key is a void pointer"<<endl;

uu u_val1, u_val2;
void
*val1, *val2;
u_val1.i = 70, val1 = &u_val1;
newMap_[val1]=u_val1;

val2 = val1;
map<void *, uu>::const_iterator it_new;
it_new = newMap_.find(val2);
if
(it_new != newMap_.end())
{

u_val2 = it_new->second;
cout<<"Note that since u_val2 is a union you can print i or c as required"<<endl;
cout<<"val2 = "<<val2<<" value.c = "<<u_val2.c<<endl;
cout<<"val2 = "<<val2<<" value.i = "<<u_val2.i<<endl;
}


return
0;
}



The output is as follows:

3 comments:

  1. Hello, nice example of maps.
    thanks

    ReplyDelete
  2. Thanks for this example!

    ReplyDelete
  3. Hello Mate,


    Great piece on Advanced C++ with Examples, I’m a fan of the ‘flowery’ style Looking forward to more long form articles ??

    I need a help for making double link list program in C double link list (file.h and file.c) in prototype insert first, insert after, insert last, delete first, delete after, and delete last.
    Awesome! Thanks for putting this all in one place. Very useful!


    Obrigado,
    Mansy

    ReplyDelete