map is a associative container. It is typically implemented as balanced binary search tree. In a balanced binary search tree, the height of its left and height of its right sub-tree are equal. A map container stores pairs of keys and values. So its item is a pair of key and value instead of a single value. It is used for fast storage and retrieval of pairs of keys and values. Given a key in map's subscript operator , its associated value is located. In default, the map sorts the pairs of keys and values by key field in ascending order. If you want to sort the pairs in descending order, you need to use the comparator function greater<T>. The map does not allow duplicate keys to be inserted. A duplicate pair will be ignored. So only a single value is associated with each key. If you want to allow duplicate keys, you will use multimap class instead. The map class has the following constructors:
-explicit map(const _Compare& __comp, const allocator_type& __a) creates an empty map object.
-map(_InputIterator __first, _InputIterator __last) creates a map object containing copies of items from first to last.
-map(const map& __x) creates a map object that contains items copied from another map object.
The frequently used member functions of the set class are insert(), erase(), begin(), end(), size(), and find(). The insert function allows you to insert a pair of key and value to the map container. The erase() function can be used to remove a specific item from the container. You can remove an item by its position or by its key. The begin() reads the first item and the end() refers to the next position after the end of the container. The size() function returns the capacity of the container. The find() function can be used to search for a specific value by key.
using namespace std;
int main(int argc, char *argv)
//create an empty map container with descending sort order
map<string,string,greater<string> > PCIPMap;
//insert key/value pairs to the container
//delete a pair that contains PC3 as its key
//display all keys and values pairs
//find a value by key
cout<<"The IP of PC2 is "<<fit->second<<".\n";
cout<<"PC2 is not found.\n";
//Count the number of items in the map
cout<<"Number of items:"<<PCIPMap.size()<<endl;
Posted by: Dara | post date: 02-07-2014 | Subject: C++ Programming Language
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages: