Map (C++): Difference between revisions
rename headings; move member functions to design; reformat |
|||
Line 11: | Line 11: | ||
[[Iterator]]s and [[Reference (C++)|reference]]s are not invalidated by insert and erase operations, except for iterators and references to erased elements. The usual implementation is a [[self-balancing binary search tree]] (but any other data structure that respects the complexity constraints can be used, like a [[skip list]]). |
[[Iterator]]s and [[Reference (C++)|reference]]s are not invalidated by insert and erase operations, except for iterators and references to erased elements. The usual implementation is a [[self-balancing binary search tree]] (but any other data structure that respects the complexity constraints can be used, like a [[skip list]]). |
||
==Design== |
|||
==Main characteristics== |
|||
===Characteristics=== |
|||
* Each element has a unique key |
* Each element has a unique key |
||
* Each element is composed of a key and a mapped value |
* Each element is composed of a key and a mapped value |
||
* Elements follow a [[strict weak ordering]]<ref name="std" /> |
* Elements follow a [[strict weak ordering]]<ref name="std" /> |
||
==Performance== |
===Performance=== |
||
Maps are designed to be especially efficient in accessing its elements by their key, as opposed to sequence containers which are more efficient in accessing elements by their position.<ref name="std" /> |
Maps are designed to be especially efficient in accessing its elements by their key, as opposed to sequence containers which are more efficient in accessing elements by their position.<ref name="std" /> |
||
Line 39: | Line 39: | ||
| Iterating through all elements || O(n) |
| Iterating through all elements || O(n) |
||
|} |
|} |
||
===Overview of functions=== |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/map map]</code> (constructor) - Constructs the map from variety of sources. |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/~map ~map]</code> (destructor) - Destructs the map and the contained elements |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/operator= operator=]</code> - Assigns values to the map |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/get_allocator get_allocator]</code> - Returns the allocator used to allocate memory for the elements |
|||
*Iterators |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/begin begin]</code> - Returns an iterator to the beginning of the map |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/end end]</code> - Returns an iterator to the end of the map |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/rbegin rbegin]</code> - Returns a reverse iterator to the reverse beginning of the map |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/rend rend]</code> - Returns a reverse iterator to the reverse end of the map |
|||
* Capacity |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/empty empty]</code> - Checks whether the map is empty |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/size size]</code> - Returns the number of elements in the map. |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/max_size max_size]</code> - Returns the maximum possible number of elements in the map. |
|||
*Modifiers |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/clear clear]</code> - Clears the contents |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/insert insert]</code> - Inserts elements |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/emplace emplace]</code> ([[C++11]]) - Constructs elements in-place |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/emplace emplace_hint]</code> ([[C++11]]) - Constructs elements in-place using a hint |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/erase erase]</code> - Erases elements |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/swap swap]</code> - Swaps the contents with another map |
|||
*Lookup |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/count count]</code> - Returns the number of elements matching specific key |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/find find]</code> - Finds an element with specific key |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/equal_range equal_range]</code> - Returns a range of elements matching specific key |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/lower_bound lower_bound]</code> - Returns an iterator to the first element not less than the given value |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/upper_bound upper_bound]</code> - Returns an iterator to the first element greater than a certain value |
|||
*Observers |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/key_comp key_comp]</code> - Returns key comparison function. |
|||
**<code>map::[http://en.cppreference.com/enwiki/w/cpp/container/map/value_comp value_comp]</code> - Returns value comparison function. |
|||
==Usage== |
==Usage== |
||
Line 149: | Line 180: | ||
// Using a const_iterator since we are not going to change the values. |
// Using a const_iterator since we are not going to change the values. |
||
MapType::const_iterator end = data.end(); |
MapType::const_iterator end = data.end(); |
||
for (MapType::const_iterator it = data.begin(); it != end; ++it) |
for (MapType::const_iterator it = data.begin(); it != end; ++it) { |
||
{ |
|||
std::cout << "Who(key = first): " << it->first; |
std::cout << "Who(key = first): " << it->first; |
||
std::cout << " Score(value = second): " << it->second << '\n'; |
std::cout << " Score(value = second): " << it->second << '\n'; |
||
Line 160: | Line 190: | ||
This will output the keys and values of the entire map, sorted by keys. |
This will output the keys and values of the entire map, sorted by keys. |
||
== Member functions == |
|||
What follows is a list of the public member functions in the <code>map</code> library:<ref name="std" /> |
|||
{| class="wikitable" |
|||
|- |
|||
! Name||Description |
|||
|- |
|||
| <code>(constructor)</code> || Construct a map object |
|||
|- |
|||
| <code>(destructor)</code> || Destroys map object |
|||
|- |
|||
| <code>operator=</code> || Copy content of container |
|||
|- |
|||
| colspan=2 align=center| '''Iterators:''' |
|||
|- |
|||
| <code>begin</code> || Return iterator to beginning of map |
|||
|- |
|||
| <code>end</code> || Return iterator to end of map |
|||
|- |
|||
| <code>rbegin</code> || Return reverse iterator to reverse beginning (end) |
|||
|- |
|||
| <code>rend</code> || Return reverse iterator to reverse end (beginning) |
|||
|- |
|||
| colspan=2 align=center| '''Capacity:''' |
|||
|- |
|||
| <code>empty</code> || Test whether map is empty or not |
|||
|- |
|||
| <code>size</code> || Return container size of map |
|||
|- |
|||
| <code>max_size</code> || Return maximum size of map |
|||
|- |
|||
| colspan=2 align=center| '''Element access:''' |
|||
|- |
|||
| <code>operator[]</code> || Access element |
|||
|- |
|||
| colspan=2 align=center| '''Modifiers:''' |
|||
|- |
|||
| <code>insert</code> || Insert element |
|||
|- |
|||
| <code>erase</code> || Erase element |
|||
|- |
|||
| <code>swap</code> || Swap contents |
|||
|- |
|||
| <code>clear</code> || Clear contents |
|||
|- |
|||
| colspan=2 align=center| '''Observers:''' |
|||
|- |
|||
| <code>key_comp</code> || Return key comparison object |
|||
|- |
|||
| <code>value_comp</code> || Return value comparison object |
|||
|- |
|||
| colspan=2 align=center| '''Operations:''' |
|||
|- |
|||
| <code>find</code> || Return iterator to element |
|||
|- |
|||
| <code>count</code> || Count elements with a specific key |
|||
|- |
|||
| <code>lower_bound</code> || Return iterator to the lower bound |
|||
|- |
|||
| <code>upper_bound</code> || Return iterator to the upper bound |
|||
|- |
|||
| <code>equal_range</code> || Return range of equal elements |
|||
|- |
|||
| colspan=2 align=center| '''Allocator:''' |
|||
|- |
|||
| <code>get_allocator</code> || Return allocator |
|||
|} |
|||
== Member types == |
== Member types == |
Revision as of 13:02, 3 October 2011
C++ Standard Library |
---|
Containers |
C standard library |
The class template std::map<Key, Data, Compare, Alloc>
is a standard C++ container. It is a sorted associative array of unique keys and associated data.[1] The types of key and data may differ, and the elements of the map are internally sorted from lowest to highest key value. Since each key value is unique, if an object is inserted with an already existing key, the object already present in the map does not change.[1] A variation on the map, called the multimap, allows duplicate keys.
Iterators and references are not invalidated by insert and erase operations, except for iterators and references to erased elements. The usual implementation is a self-balancing binary search tree (but any other data structure that respects the complexity constraints can be used, like a skip list).
Design
Characteristics
- Each element has a unique key
- Each element is composed of a key and a mapped value
- Elements follow a strict weak ordering[1]
Performance
Maps are designed to be especially efficient in accessing its elements by their key, as opposed to sequence containers which are more efficient in accessing elements by their position.[1]
The asymptotic complexity of the operations that can be applied to maps are as follows:
Operation | Complexity |
---|---|
Searching for an element | O(log n) |
Inserting a new element | O(log n) |
Incrementing/decrementing an iterator | O(log n) |
Removing a single map element | O(log n) |
Copying an entire map [1] | O(n) |
Iterating through all elements | O(n) |
Overview of functions
map::map
(constructor) - Constructs the map from variety of sources.map::~map
(destructor) - Destructs the map and the contained elementsmap::operator=
- Assigns values to the mapmap::get_allocator
- Returns the allocator used to allocate memory for the elements
- Iterators
- Capacity
- Modifiers
- Lookup
map::count
- Returns the number of elements matching specific keymap::find
- Finds an element with specific keymap::equal_range
- Returns a range of elements matching specific keymap::lower_bound
- Returns an iterator to the first element not less than the given valuemap::upper_bound
- Returns an iterator to the first element greater than a certain value
- Observers
map::key_comp
- Returns key comparison function.map::value_comp
- Returns value comparison function.
Usage
The map is declared in this format:
map <key_type, value_type [, comparing_option [, memory_allocator] ] > map_name
The following code demonstrates how to use the map<string, int>
to count occurrences of words. It uses the word as the key and the count as the value.
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, int> wordcounts;
std::string s;
while (std::cin >> s && s != "end")
++wordcounts[s];
while (std::cin >> s && s != "end")
std::cout << s << ' ' << wordcounts[s] << '\n';
}
When executed, the user first types a series of words separated by spaces, and a word "end" to signify the end of input; then the user can input words to query how many times each word occurred in the previous series.
The above example also demonstrates that the operator [] inserts new objects (using the default constructor) in the map if there isn't one associated with the key. So integral types are zero-initialized, strings are initialized to empty strings, etc.
The following example illustrates inserting elements into a map using the insert function and searching for a key using a map iterator and the find function:
#include <iostream>
#include <map>
#include <utility> // make_pair
int main()
{
typedef std::map<char, int> MapType;
MapType my_map;
// insert elements using insert function
my_map.insert(std::pair<char, int>('a', 1));
my_map.insert(std::pair<char, int>('b', 2));
my_map.insert(std::pair<char, int>('c', 3));
my_map.insert(MapType::value_type('d', 4)); // all standard containers provide this typedef
my_map.insert(std::make_pair('e', 5)); // can also use the utility function make_pair
//map keys are sorted automatically from lower to higher.
//So, my_map.begin() points to the lowest key value not the key which was inserted first.
MapType::iterator iter = my_map.begin();
// erase the first element using the erase function
my_map.erase(iter);
// output the size of the map
std::cout << "Size of my_map: " << my_map.size() << '\n';
std::cout << "Enter a key to search for: ";
char c;
std::cin >> c;
// find will return an iterator to the matching element if it is found
// or to the end of the map if the key is not found
iter = my_map.find(c);
if (iter != my_map.end() )
std::cout << "Value is: " << iter->second << '\n';
else
std::cout << "Key is not in my_map" << '\n';
// clear the entries in the map
my_map.clear();
}
In the above example, five elements are entered using the insertion function, and then the first element is deleted. Then, the size of the map is output. Next, the user is prompted for a key to search for. Using the iterator, the find function searches for an element with the given key. If it finds the key, the program prints the element's value. If it does not find it, an iterator to the end of the map is returned and it outputs that the key could not be found. Finally all the elements in the tree are erased.
Iterators
Maps may use iterators to point to specific elements in the container. An iterator can access both the key and the mapped value of an element:[1]
map<Key,T>::iterator it; // declares a map iterator
it->first; // the key value
it->second; // the mapped value
(*it); // the "element value", which is of type: pair<const Key,T>
Below is an example of looping through a map to display all keys and values using iterators:
#include <iostream>
#include <string>
#include <map>
int main()
{
typedef std::map <std::string, int> MapType;
MapType data;
// let's declare some initial values to this map
data["Bobs score"] = 10;
data["Martys score"] = 15;
data["Mehmets score"] = 34;
data["Rockys score"] = 22;
data["Rockys score"] = 23; /*overwrites the 22 as keys are unique */
// Iterate over the map and print out all key/value pairs.
// Using a const_iterator since we are not going to change the values.
MapType::const_iterator end = data.end();
for (MapType::const_iterator it = data.begin(); it != end; ++it) {
std::cout << "Who(key = first): " << it->first;
std::cout << " Score(value = second): " << it->second << '\n';
}
return 0;
}
This will output the keys and values of the entire map, sorted by keys.
Member types
What follows is a list of the member types of the map
container:[1]
Member type | Definition |
---|---|
key_type |
Key |
mapped_type |
T
|
value_type |
pair<const Key,T>
|
key_compare |
Compare |
value_compare |
Nested class to compare elements |
allocator_type |
Allocator
|
reference |
Allocator::reference
|
const_reference |
Allocator::const_reference
|
iterator |
Bidirectional iterator |
const_iterator |
Constant bidirectional iterator |
size_type |
Unsigned integral type (usually same as size_t )
|
difference_type |
Signed integral type (usually same as ptrdiff_t )
|
pointer |
Allocator::pointer
|
const_pointer |
Allocator::const_pointer
|
reverse_iterator |
reverse_iterator<iterator>
|
const_reverse_iterator |
reverse_iterator<const_iterator>
|
Caveats
Because map requires a strict weak ordering, a map keyed on floating-point numbers can produce undefined behavior if any of the keys are NaNs.