FAQ 28.14 What are the best situations for the standardized C associative container classes?

FAQ 28.14 What are the best situations for the standardized C++ associative container classes?

graphics/new_icon.gif

Operations that make sense for keyed containers of objects.

The associative container classes store their objects so that the keys are in a sorted order based on a comparison object or function. They include the following container classes.

  • set<T>

  • multiset<T>

  • map<Key,Value>

  • multimap<Key,Value>

They all expand to allow an arbitrary number of elements to be inserted, and all provide numerous operations. set<T> and multiset<T> allow the insertion, lookup, and removal of keys, with multiset<T> allowing multiple copies of the same key value (some libraries use the term "bag" for this). map<Key,Value> and multimap<Key,Value> allow values to be inserted, looked up, and removed by their key, with multiset<T> allowing multiple values associated with the same key value.

Here are some selected ways to use the standard map<Key,Value> class.

 #include <string> #include <map> #include <iostream> using namespace std; typedef  map<string,int>  AgeMap;                    <-- 1 int main() {   AgeMap age;   // The subscript operator is used to access an element in the map   age["Fred"] = 42;   age["Barney"] = 38;   int n = age["Fred"];   int numElements = age.size();   // Removing an element from the map   age.erase("Barney");   // Iterators are used to loop through all the elements within the map   for (AgeMap::iterator p = age.begin(); p != age.end(); ++p)     cout << "age of " << p->first << " is " << p->second << "\n";   // Iterators can be used to check if an entry is in the map   AgeMap::const_iterator q = age.find("Fred");   if (q == age.end())     cout << "Fred isn't in the map\n";   else     cout << "Fred is in the map; his age is " << q->second << "\n"; } 

(1) A typedef can make the rest easier to read



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net