Associate words with the STL map

Please support our C++ advertiser: Intel Parallel Studio Home
vegaseat vegaseat is offline Offline Nov 29th, 2004, 9:31 pm |
0
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.
Quick reply to this message  
C++ Syntax
  1. // experimenting with the STL map<const Key, Data>
  2. // const Key is unique, no two elements can have the same key
  3. // building a simple associated word search
  4. // a Dev-C++ tested console application by vegaseat 29nov2004
  5.  
  6. #include <iostream>
  7. #include <map> // map, pair
  8.  
  9. using namespace std; // std::cout, std::cin
  10.  
  11. int main()
  12. {
  13. char thing[30]; // key word
  14. char farbe[30]; // associated color
  15. map<string,string> sM; // map<const Key, Data>
  16. map<string,string>::iterator iter; // points to elements
  17.  
  18. // load the map<string,string> with things and color
  19. // could be loaded from a data file too
  20. sM.insert(pair<string,string>("rose","red"));
  21. sM.insert(pair<string,string>("sky","blue"));
  22. sM.insert(pair<string,string>("coal","black"));
  23. sM.insert(pair<string,string>("blood","red"));
  24. sM.insert(pair<string,string>("snow","white"));
  25. sM.insert(pair<string,string>("fire","red"));
  26.  
  27. // list the things (key words)
  28. cout << "things to choose from:\n";
  29. for(iter = sM.begin(); iter != sM.end(); iter++)
  30. {
  31. cout<< iter->first << endl;
  32. }
  33.  
  34. cout << "Enter a thing: ";
  35. cin >> thing;
  36. // find the specified thing (unique key word)
  37. // point to the map's end if find fails
  38. iter = sM.find(thing); // point to it
  39. if (iter != sM.end())
  40. {
  41. cout << "the " << iter->first << " is " << iter->second << endl;
  42. }
  43. else
  44. {
  45. cout << "thing " << thing << " not found!" << endl;
  46. }
  47.  
  48. // you can look for the associated word (not unique)
  49. cout << "all the red things:\n";
  50. for(iter = sM.begin(); iter != sM.end(); iter++)
  51. {
  52. if (iter->second == "red")
  53. cout << iter->first << " is " << iter->second << endl;
  54. }
  55.  
  56. cin.get(); // trap return
  57. cin.get(); // wait
  58. return 0;
  59. }
  60.  

Message:


Similar Threads
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC