FAQ 28.14 What are the best situations for the standardized C++ associative container classes?
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.
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"; }
|