Skip to content

C++ <map> API

C++ std::map — an ordered associative container of key-value pairs, implemented as a red-black tree.

1 class · 6 methods

std::map

6 methods

An 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

NameTypeDescription
valconst 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 unchanged
std::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

NameTypeDescription
kconst 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_range
std::map::size() const noexcept -> size_t

Returns 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();  // 2
std::map::erase(const key_type& k) -> size_type

Removes the element with key k. Returns the number of elements removed (0 or 1).

Parameters

NameTypeDescription
kconst 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"); // 0
std::map::find(const key_type& k) -> iterator

Returns an iterator to the element with key k, or end() if not found.

Parameters

NameTypeDescription
kconst 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 -> bool

Returns true if the container has no elements.

Returns

bool

Example

cpp
std::map<std::string, int> m;
if (m.empty()) {
    std::cout << "empty\n";
}