My program needs a way to store key-value pairs, STLs map class seems to fit the purpose quite well. Both the key and the value are string classes.
My problem is twofold. One, I have no idea about how to use this class. In particular I mean the last template parameter. Two, all the example code I have in SGI''s docs only access the pairs via iterator, and I need to simply get the value given the key (I assume map does this, but I can''t figure out how either).
Thanx!!!!!
-Solstice
deninet.com
aeris.deninet.com
"...I was given three choices, the earth, the stars, or..."
Maps are really quite simple. You can access values directly using the key with array notation. Here''s a quick example:
#include <map>#include <string>int main(int argc, char* argv){ std::map< std::string, std::string> myMap; myMap["Hello"] = " world"; myMap["Goodbye"] = " everyone"; myMap["GameDev"] = ".net"; std::map< std::string, std::string >::iterator i; for(i = myMap.begin(); i != myMap.end(); ++i) { std::cout << i->first << i->second << std::endl; } std::string someWord = myMap["GameDev"]; std::cout << "Word: " << someWord << endl; return 0;}
The third parameter is a comparison functor, which generally you can leave it to the default.
The quick & dirty way to insert & access stuff in a map, is to use the overloaded operator[].
The quick & dirty way to insert & access stuff in a map, is to use the overloaded operator[].
#include <map> #include <string> typedef std::map<std::string, std::string> str2str_t;str2str_t str2str;str2str["Alpha"] = "a";str2str["Beta"] = "b";//prints ''a''cout << str2str["Alpha"] << std::endl;
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement