📅  最后修改于: 2023-12-03 14:39:51.091000             🧑  作者: Mango
Map is a data structure in C++ STL that stores keys and its corresponding values. It is implemented using self-balancing binary search trees like Red-Black Tree or AVL Tree. It stores the keys in sorted order and provides fast searching, insertion, and deletion of elements.
The syntax for declaring a map is as follows:
std::map<key_data_type, value_data_type> map_name;
key_data_type
is the data type of the key and value_data_type
is the data type of the value.
#include <map>
#include<string>
std::map<int, std::string> employee_map;
We can insert elements in a map using the insert()
function.
employee_map.insert(std::pair<int, std::string>(1, "John"));
employee_map.insert(std::make_pair(2, "Mary"));
employee_map[3] = "Jessica";
We can access elements in a map using operator[]
or the at()
function.
std::cout << employee_map[1] << std::endl; // John
std::cout << employee_map.at(2) << std::endl; // Mary
We can iterate through a map using for each
loop.
for (const auto& employee: employee_map)
{
std::cout << "Employee Id: " << employee.first
<< ", Name: " << employee.second << std::endl;
}
We can erase an element from a map using erase()
function.
employee_map.erase(1); // erases element with key 1
We can get the size of a map using size()
function.
std::cout << employee_map.size() << std::endl; // 2
We can clear a map using clear()
function.
employee_map.clear(); // clears the map
Map in C++ STL is a powerful and efficient data structure that provides fast searching, insertion, and deletion of elements. It is widely used in many applications where fast access to key-value pairs is necessary.