map::operator
inserta un elemento en un mapa con un valor de clave especificado.
Type& operator[](
const Key& _Key
);
Type& operator0-(
Key&& _Key
);
Parámetros
Parámetro |
Descripción |
_Key |
El valor de la clave del elemento que se va a insertar. |
Valor devuelto
Una referencia al valor de los datos del elemento insertado.
Comentarios
Si el valor de clave de argumento no se encuentra, se incrusta junto con el valor predeterminado del tipo de datos.
operator[] se puede utilizar para insertar elementos en un mapa m mediante m[_Key] = DataValue; donde el valor DataValue de mapped_type de elemento con un valor de clave de _Key.
Al utilizar operator[] para insertar elementos, la referencia devuelta no indica si una inserción cambia un elemento existente o está creando un nuevo.Las funciones búsqueda y inserción miembro se pueden utilizar para determinar si un elemento con una clave especificada ya exista antes de una inserción.
Ejemplo
// map_op_insert.cpp
// compile with: /EHsc
#include <map>
#include <iostream>
#include <string>
int main( )
{
using namespace std;
typedef pair <const int, int> cInt2Int;
map <int, int> m1;
map <int, int> :: iterator pIter;
// Insert a data value of 10 with a key of 1
// into a map using the operator[] member function
m1[ 1 ] = 10;
// Compare other ways to insert objects into a map
m1.insert ( map <int, int> :: value_type ( 2, 20 ) );
m1.insert ( cInt2Int ( 3, 30 ) );
cout << "The keys of the mapped elements are:";
for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
cout << " " << pIter -> first;
cout << "." << endl;
cout << "The values of the mapped elements are:";
for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
cout << " " << pIter -> second;
cout << "." << endl;
// If the key already exists, operator[]
// changes the value of the datum in the element
m1[ 2 ] = 40;
// operator[] will also insert the value of the data
// type's default constructor if the value is unspecified
m1[5];
cout << "The keys of the mapped elements are now:";
for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
cout << " " << pIter -> first;
cout << "." << endl;
cout << "The values of the mapped elements are now:";
for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
cout << " " << pIter -> second;
cout << "." << endl;
// insert by moving key
map<string, int> c2;
string str("abc");
cout << "c2[move(str)] == " << c2[move(str)] << endl;
cout << "c2["abc"] == " << c2["abc"] << endl;
return (0);
}
Requisitos
encabezado: <Asignar>
espacio de nombres: std