hash_map::operator[]
Inserts an element into a hash_map with a specified key value.
Type& operator[](
const Key& _Key
);
Parameters
- _Key
The key value of the element that is to be inserted.
Return Value
A reference to the data value of the inserted element.
Remarks
If the argument key value is not found, then it is inserted along with the default value of the data type.
operator[]may be used to insert elements into a hash_map m using m[_Key] = DataValue; where DataValue is the value of the mapped_type of the element with a key value of _Key.
When using operator[] to insert elements, the returned reference does not indicate whether an insertion is changing a preexisting element or creating a new one. The member functions find and insert can be used to determine whether an element with a specified key is already present before an insertion.
In Visual C++ .NET 2003, members of the <hash_map> and <hash_set> header files are no longer in the std namespace, but rather have been moved into the stdext namespace. See The stdext Namespace for more information.
Example
// hash_map_op_ref.cpp
// compile with: /EHsc
#define _DEFINE_DEPRECATED_HASH_CLASSES 0
#include <hash_map>
#include <iostream>
int main( )
{
using namespace std;
using namespace stdext;
typedef pair <const int, int> cInt2Int;
hash_map <int, int> hm1;
hash_map <int, int> :: iterator pIter;
// Insert a data value of 10 with a key of 1
// into a hash_map using the operator[] member function
hm1[ 1 ] = 10;
// Compare other ways to insert objects into a hash_map
hm1.insert ( hash_map <int, int> :: value_type ( 2, 20 ) );
hm1.insert ( cInt2Int ( 3, 30 ) );
cout << "The keys of the mapped elements are:";
for ( pIter = hm1.begin( ) ; pIter != hm1.end( ) ; pIter++ )
cout << " " << pIter -> first;
cout << "." << endl;
cout << "The values of the mapped elements are:";
for ( pIter = hm1.begin( ) ; pIter != hm1.end( ) ; pIter++ )
cout << " " << pIter -> second;
cout << "." << endl;
// If the key already exists, operator[]
// changes the value of the datum in the element
hm1[ 2 ] = 40;
// operator[] will also insert the value of the data
// type's default constructor if the value is unspecified
hm1[5];
cout << "The keys of the mapped elements are now:";
for ( pIter = hm1.begin( ) ; pIter != hm1.end( ) ; pIter++ )
cout << " " << pIter -> first;
cout << "." << endl;
cout << "The values of the mapped elements are now:";
for ( pIter = hm1.begin( ) ; pIter != hm1.end( ) ; pIter++ )
cout << " " << pIter -> second;
cout << "." << endl;
}
Output
The keys of the mapped elements are: 1 2 3.
The values of the mapped elements are: 10 20 30.
The keys of the mapped elements are now: 1 2 3 5.
The values of the mapped elements are now: 10 40 30 0.
Requirements
Header: <hash_map>
Namespace: stdext