In computing, associative containers refer to a group of class templates in the
standard library
In computer programming, a standard library is the library made available across implementations of a programming language. These libraries are conventionally described in programming language specifications; however, contents of a language's as ...
of the
C++ programming language
C (''pronounced like the letter c'') is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of ...
that implement ordered
associative arrays.
Being
templates
Template may refer to:
Tools
* Die (manufacturing), used to cut or shape material
* Mold, in a molding process
* Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs
Co ...
, they can be used to store arbitrary elements, such as integers or custom classes. The following containers are defined in the current revision of the C++ standard:
set
,
map
,
multiset
,
multimap
. Each of these containers differ only on constraints placed on their elements.
The associative containers are similar to the
unordered associative containers in
C++ standard library, the only difference is that the unordered associative containers, as their name implies, do not
order
Order, ORDER or Orders may refer to:
* Categorization, the process in which ideas and objects are recognized, differentiated, and understood
* Heterarchy, a system of organization wherein the elements have the potential to be ranked a number of d ...
their elements.
Design
Characteristics
* Key uniqueness: in
map
and
set
each key must be unique.
multimap
and
multiset
do not have this restriction.
* Element composition: in
map
and
multimap
each element is composed from a key and a mapped value. In
set
and
multiset
each element is key; there are no mapped values.
* Element ordering: elements follow a
strict weak ordering
In mathematics, especially order theory, a weak ordering is a mathematical formalization of the intuitive notion of a ranking of a set, some of whose members may be tied with each other. Weak orders are a generalization of totally ordered se ...
Associative containers 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.
Associative containers are guaranteed to perform operations of insertion, deletion, and testing whether an element is in it, in logarithmic time – O(log ''n''). As such, they are typically implemented using
self-balancing binary search trees and support bidirectional iteration.
Iterators and
reference
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''name'' ...
s are not invalidated by insert and erase operations, except for iterators and references to erased elements.The defining characteristic of associative containers is that elements are inserted in a pre-defined order, such as sorted ascending.
The associative containers can be grouped into two subsets: maps and sets. A map, sometimes referred to as a dictionary, consists of a key/value pair. The key is used to order the sequence, and the value is somehow associated with that key. For example, a map might contain keys representing every unique word in a text and values representing the number of times that word appears in the text. A set is simply an ascending container of unique elements.
As stated earlier,
map
and
set
only allow one instance of a key or element to be inserted into the container. If multiple instances of elements are required, use
multimap
or
multiset
.
Both maps and sets support bidirectional iterators. For more information on iterators, see
Iterators.
While not officially part of the
STL STL may refer to:
Communications
* Standard telegraph level
*Studio/transmitter link
International law
*Special Tribunal for Lebanon
The Special Tribunal for Lebanon (STL), also referred to as the Lebanon Tribunal or the Hariri Tribunal, is a ...
standard,
hash_map
and
hash_set
are commonly used to improve searching times. These containers store their elements as a
hash table, with each table entry containing a bidirectional
linked list
In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes whic ...
of elements. To ensure the fastest search times (''O(1)''), make sure that the hashing algorithm for your elements returns evenly distributed hash values.
Performance
The
asymptotic complexity of the operations that can be applied to associative containers are as follows:
Overview of functions
The containers are defined in headers named after the names of the containers, e.g.
set
is defined in header
. All containers satisfy the requirements of th
Containerconcept
Concepts are defined as abstract ideas. They are understood to be the fundamental building blocks of the concept behind principles, thoughts and beliefs.
They play an important role in all aspects of cognition. As such, concepts are studied by s ...
, which means they have
begin()
,
end()
,
size()
,
max_size()
,
empty()
, and
swap()
methods.
Usage
The following code demonstrates how to use the
map
to count occurrences of words. It uses the word as the ''key'' and the count as the ''value''.
#include
#include
When executed, program lets user type a series of words separated by spaces, and a word "end" to signify the end of input. Then user can input a word to query how many times it has occurred in the previously entered series.
The above example also demonstrates that the operator
[]
inserts new objects (using the default constructor) in the map if there is not 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
#include
Example shown above demostrates the usage of some of the functions provided by
map
, such as
insert()
(place element into the map),
erase()
(remove element from the map),
find()
(check presence of the element in the container), etc.
When program is executed, six elements are inserted using the
insert()
function, then the first element is deleted using
erase()
function and the size of the map is outputted. Next, the user is prompted for a key to search for in the map. Using the iterator created earlier, 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 doesn't 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 using
clear()
.
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:
// Declares a map iterator
std::map::iterator it;
// Accesses the Key value
it->first;
// Accesses the mapped value
it->second;
// The "value" of the iterator, which is of type std::pair
(*it);
Below is an example of looping through a map to display all keys and values using iterators:
#include
#include
For compiling above sample on GCC compiler, must use specific standard select flag.
g++ -std=c++11 source.cpp -o src
This will output the keys and values of the entire map, sorted by keys.
See also
*
Container (abstract data type)
*
Standard Template Library#Containers
*
Unordered associative containers C++
References
{{reflist
C++ Standard Library
Associative arrays