Another experiment with the Standard Template Library (STL). This time we are taking a look at map. Map is a Sorted Pair Associative Container (a mouthful). The pair is -- const Key, Data --, where Key has to be unique. It is Key that is sorted. In this code sample a simple word association is shown. The map is loaded, displayed, and searched.
Associate words with the STL map
// experimenting with the STL map<const Key, Data>
// const Key is unique, no two elements can have the same key
// building a simple associated word search
// a Dev-C++ tested console application by vegaseat 29nov2004
#include <iostream>
#include <map> // map, pair
using namespace std; // std::cout, std::cin
int main()
{
char thing[30]; // key word
char farbe[30]; // associated color
map<string,string> sM; // map<const Key, Data>
map<string,string>::iterator iter; // points to elements
// load the map<string,string> with things and color
// could be loaded from a data file too
sM.insert(pair<string,string>("rose","red"));
sM.insert(pair<string,string>("sky","blue"));
sM.insert(pair<string,string>("coal","black"));
sM.insert(pair<string,string>("blood","red"));
sM.insert(pair<string,string>("snow","white"));
sM.insert(pair<string,string>("fire","red"));
// list the things (key words)
cout << "things to choose from:\n";
for(iter = sM.begin(); iter != sM.end(); iter++)
{
cout<< iter->first << endl;
}
cout << "Enter a thing: ";
cin >> thing;
// find the specified thing (unique key word)
// point to the map's end if find fails
iter = sM.find(thing); // point to it
if (iter != sM.end())
{
cout << "the " << iter->first << " is " << iter->second << endl;
}
else
{
cout << "thing " << thing << " not found!" << endl;
}
// you can look for the associated word (not unique)
cout << "all the red things:\n";
for(iter = sM.begin(); iter != sM.end(); iter++)
{
if (iter->second == "red")
cout << iter->first << " is " << iter->second << endl;
}
cin.get(); // trap return
cin.get(); // wait
return 0;
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.