Tuesday, 17 March 2009

An example of bound C++ maps

The following example shows how to define a bound C++ map which can only contain maximum number of specified elements. This is just an approach and there will probably be better and more efficient approaches.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//The example below shows a bound map. In a general C++ map you
//can add as many elements as required. In this case there can
//only be 10 elements in the map. If you try adding more it will
//generate an error
#include<iostream>
#include<map>
#include<string>
#include<assert.h>

using namespace
std;

map<int, string> freq;
int
a[10]={0,0,0,0,0,0,0,0,0,0};

int
store_in_maps(string s)
{

int
i;
for
(i=0; i < 10; i++)
{

if
(a[i]==0)
break
;
}

if
(i==10)
{

cout<<"Sorry no more Ids available in the pool"<<endl;
assert(0);
}


a[i]=1;
freq[i] = s;
return
i;
}


int
remove_from_map(string s)
{

map<int, string>::const_iterator iter;
for
(iter=freq.begin(); iter != freq.end(); ++iter)
{

if
(iter->second == s)
break
;
}

if
(iter==freq.end())
{

cout<<"Cant find the string "<<s<<endl;
return
(-1);
}

a[iter->first]=0;
return
iter->first;
}



int
main()
{

store_in_maps("first");
store_in_maps("second");
store_in_maps("third");
store_in_maps("fourth");
store_in_maps("fifth");
store_in_maps("sixth");
store_in_maps("seventh");
store_in_maps("eighth");
store_in_maps("ninth");
store_in_maps("tenth");
remove_from_map("fifth");
store_in_maps("eleventh");
remove_from_map("zahid");
remove_from_map("fourth");

map<int, string>::const_iterator iter;
for
(iter=freq.begin(); iter != freq.end(); ++iter)
{

cout<<"First: "<<(iter->first)<<" Second: "<<(iter->second)<<"\t\tPool value: "<<a[iter->first]<<endl;
}


return
0;
}



The output of the program is as follows:

No comments:

Post a Comment