![]() |
VOOZH | about |
C++23 introduces a new header, <flat_map>, for storing key-value pairs in a more cache-friendly and efficient manner. It provides an alternative to traditional associative containers like std::map and std::unordered_map.
std::flat_map is a container introduced in C++23 for storing key-value pairs. It combines features of std::map and std::vector:
To use it, include the <flat_map> header and declare it with the required key and value types.
std::flat_map < keyType, valueType > name;We can initialize a flat_map container in C++ using the following methods:
We can initialize std::flat_map by proving key and value pairs in the initializer list.
std::flat_map<int, string> object_name { {3, "three"}, {1, "one"}, {4, "four"} };We can use the range constructor to initialize the std::flat_map object with key and value pairs by specifying the range using the starting iterator and ending iterator.
flat_map <keyType, valueType > object_name(startingIterator, endingIterator);
We can simply initialize the flat_map object object with another already existing flat_map object using an assignment operator.
std::flat_map <keyType, valueType > object_name;
object_name = prev_object;We can initialize a std::flat_map using the move assignment operator. This way of initializing a std::flat_map is memory efficient because the assigned object simply points to the existing memory location where the data is stored without creating unnecessary copies of data.
std::flat_map <keyType, valueType > object_name; object_name = move(prev_object);
Output
Key: 1, Value: Geeks
Key: 2, Value: Geeks
Key: 3, Value: forThe following are some member functions for basic operation on the flat_map container:
Iterators are used to traverse the container. The following function returns iterators to the flat_map containers:
Example
Output
All key-value pairs in the map:
Key: 1, Value: Geeks
Key: 2, Value: for
Key: 3, Value: Geeks
Key: 4, Value: CodingExample
Output
Map before erasing:
Key: 1, Value: Geeks
Key: 2, Value: for
Key: 3, Value: Geeks
Key: 4, Value: Coding
Map after erasing by key:
Key: 1, Value: Geeks
Key: 2, Value: for
Key: 4, Value: Coding
The map is empty after clearing.Example
Output
Size of the map: 3
Maximum possible size of the map: 256204778801521550
The map is not empty.Example
Output
Key 2 exists in the map.
Value at key 3: Geeks
Number of occurrences of key 2: 1