STL map

Started by
2 comments, last by Solstice 21 years, 9 months ago
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..."
-Solsticedeninet.comaeris.deninet.com"...I was given three choices, the earth, the stars, or..."
Advertisement
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;}  
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
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[].

  #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;  
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Even with the default functor, is accessing values using [] still nice and fast?

-Solstice

deninet.com
aeris.deninet.com

"...I was given three choices, the earth, the stars, or..."
-Solsticedeninet.comaeris.deninet.com"...I was given three choices, the earth, the stars, or..."

This topic is closed to new replies.

Advertisement