📜  C++ STL-map(1)

📅  最后修改于: 2023-12-03 14:39:51.091000             🧑  作者: Mango

C++ STL Map

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.

Declaration and Initialization

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;
Insertion

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";
Accessing Elements

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
Iterating

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;
    }
Erasing

We can erase an element from a map using erase() function.

    employee_map.erase(1); // erases element with key 1
Map size and clearing

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
Conclusion

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.