📜  C++ Map(1)

📅  最后修改于: 2023-12-03 15:13:54.640000             🧑  作者: Mango

C++ Map

C++ Map is a container that stores elements in key-value pairs. It is part of the Standard Template Library (STL) in C++.

Features
  • Stores unique keys in a sorted order.
  • Provides fast search, insertion, and deletion operations.
  • It is implemented as a self-balancing binary search tree (BST).
Declaration

The syntax to declare a map is as follows:

std::map<key_type, value_type> map_name;

Here, key_type is the type of the key and value_type is the type of the value.

Insertion

We can insert elements into the map using the insert() method. The syntax for inserting an element is as follows:

map_name.insert(std::make_pair(key, value));

Here, key is the key and value is the corresponding value to be inserted.

Accessing Elements

We can access elements in the map using the square bracket [] operator. The syntax for accessing an element is as follows:

map_name[key];

Here, key is the key whose corresponding value needs to be accessed.

Traversing Map

We can traverse the map using an iterator. The syntax for traversing the map is as follows:

for(auto it = map_name.begin(); it != map_name.end(); it++)
{
    std::cout << "Key: " << it->first << " Value: " << it->second << std::endl;
}

Here, it is the iterator that iterates through all the elements of the map.

Example
#include <iostream>
#include <map>

int main()
{
    std::map<std::string, int> ages;

    ages.insert(std::make_pair("John", 25));
    ages.insert(std::make_pair("Mike", 35));
    ages.insert(std::make_pair("Alice", 20));

    std::cout << "John is " << ages["John"] << " years old." << std::endl;

    std::cout << "\nElements in the map:" << std::endl;
    for(auto it = ages.begin(); it != ages.end(); it++)
    {
        std::cout << "Key: " << it->first << " Value: " << it->second << std::endl;
    }

    return 0;
}

Output:

John is 25 years old.

Elements in the map:
Key: Alice Value: 20
Key: John Value: 25
Key: Mike Value: 35
Conclusion

C++ Map is a powerful container that provides fast lookup, insertion, and deletion operations. It is useful in scenarios where we need to store data in key-value pairs and access it using keys.