•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the C++ section within the Software Development category of DaniWeb, a massive community of 402,505 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,789 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C++ advertiser: Programming Forums
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.
// 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; }
Post Comment
•
•
•
•
DaniWeb Marketplace (Sponsored Links)