std::map
6 methodsAn ordered associative container that contains key-value pairs with unique keys, sorted by key.
std::map::insert(const value_type& val) -> pair<iterator, bool>Inserts a {key, value} pair. Returns {iterator, bool} where bool is false if the key already existed.
Parameters
| Name | Type | Description |
|---|---|---|
| val | const value_type& | Key-value pair to insert. |
Returns
pair<iterator, bool>
Example
cpp
#include <map>
std::map<std::string, int> m;
auto [it, ok] = m.insert({"a", 1});
// ok == true, it points to {"a", 1}
auto [it2, ok2] = m.insert({"a", 2});
// ok2 == false, existing value unchangedstd::map::at(const key_type& k) -> mapped_type&Returns a reference to the mapped value of k, throwing std::out_of_range if not found.
Parameters
| Name | Type | Description |
|---|---|---|
| k | const key_type& | Key to look up. |
Returns
mapped_type&
Example
cpp
std::map<std::string, int> m = {{"a", 1}};
int v = m.at("a"); // 1
// m.at("b"); // throws std::out_of_rangestd::map::size() const noexcept -> size_tReturns the number of elements in the container.
Returns
size_t
Example
cpp
std::map<std::string, int> m = {{"a", 1}, {"b", 2}};
size_t n = m.size(); // 2std::map::erase(const key_type& k) -> size_typeRemoves the element with key k. Returns the number of elements removed (0 or 1).
Parameters
| Name | Type | Description |
|---|---|---|
| k | const key_type& | Key of the element to remove. |
Returns
size_type
Example
cpp
std::map<std::string, int> m = {{"a", 1}, {"b", 2}};
size_t removed = m.erase("a"); // 1
size_t removed2 = m.erase("z"); // 0std::map::find(const key_type& k) -> iteratorReturns an iterator to the element with key k, or end() if not found.
Parameters
| Name | Type | Description |
|---|---|---|
| k | const key_type& | Key to find. |
Returns
iterator
Example
cpp
std::map<std::string, int> m = {{"a", 1}};
auto it = m.find("a");
if (it != m.end()) {
std::cout << it->second; // 1
}std::map::empty() const noexcept -> boolReturns true if the container has no elements.
Returns
bool
Example
cpp
std::map<std::string, int> m;
if (m.empty()) {
std::cout << "empty\n";
}