std::map operator[]
- since C++11
- since C++98
// (1) Non const version only
T& operator[]( const Key& key );
// (2) Non const version only
T& operator[]( Key&& key );
// (1) Non const version only
T& operator[]( const Key& key );
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
- since C++11
- until C++11
(1) Inserts a value_type object constructed in-place from std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>() if the key does not exist.
Since C++17 this function is equivalent to return this->try_emplace(key).first->second.
When the default allocator is used, this results in the key being copy constructed from key and the mapped value being value-initialized.
Type requirements
value_typemust be EmplaceConstructible fromstd::piecewise_construct,std::forward_as_tuple(key),std::tuple<>(). When the default allocator is used, this means thatkey_typemust be CopyConstructible andmapped_typemust be DefaultConstructible.
(2) Inserts a value_type object constructed in-place from std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::tuple<>() if the key does not exist.
Since C++17 this function is equivalent to return this->try_emplace(key).first->second.
When the default allocator is used, this results in the key being move constructed from key and the mapped value being value-initialized.
Type requirements
value_typemust be EmplaceConstructible fromstd::piecewise_construct,std::forward_as_tuple(std::move(key)),std::tuple<>(). When the default allocator is used, this means thatkey_typemust be MoveConstructible andmapped_typemust be DefaultConstructible.
(1) Inserts value_type(key, T()) if the key does not exist. This function is equivalent to return insert(std::make_pair(key, T())).first->second
If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.
Type requirements
key_typemust meet the requirements of CopyConstructible.mapped_typemust meet the requirements of CopyConstructible and DefaultConstructible.
Parameters
key- the key of the element to find
Return value
Reference to the mapped value of the new element if no element with key key existed. Otherwise a reference to the mapped value of the existing element whose key is equivalent to key.
Exceptions
If an exception is thrown by any operation, the insertion has no effect.
Complexity
Logarithmic in the size of the container.
Example
#include <iostream>
#include <map>
auto main() -> int {
std::map<std::string, int> playersScores = {
{ "player1", 50 },
{ "super_coder", 100 },
{ "andrew111", 41 }
};
std::cout << "player1 zdobył " << playersScores["player1"] << " punktów.\n";
std::cout << "super_cader zdobył " << playersScores["super_cader"] << " punktów.\n";
}
player1 zdobył 50 punktów.
super_cader zdobył 0 punktów.
Hover to see the original license.