📜  c++ std map initializer list - C++ (1)

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

C++ std::map Initializer List

The std::map container in C++ is a part of the Standard Template Library (STL) that associates keys with values in a sorted order. It is implemented as a balanced binary search tree, and therefore provides logarithmic time complexity for operations such as search, insertion and deletion.

In C++11, an initializer list can be used to initialize a map with a list of key-value pairs, thus making the code more readable and concise.

Syntax

The syntax to create a map using an initializer list is as follows:

std::map<key_type, value_type> myMap = { {key1, value1}, {key2, value2}, {key3, value3} };

Here, key_type and value_type are the data types of the keys and values, respectively. myMap is the name of the map. The keys and corresponding values are enclosed in braces { }, and are separated by commas ,.

Example

Let us consider the following example:

#include <iostream>
#include <map>

int main() {
  std::map<int, std::string> myMap = {{1, "Apple"}, {2, "Banana"}, {3, "Cherry"}};

  for (auto const& pair: myMap) {
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
  }

  return 0;
}

Output:

Key: 1, Value: Apple
Key: 2, Value: Banana
Key: 3, Value: Cherry

Here, we create a map myMap with three key-value pairs using an initializer list. The keys are of type int, and the values are of type std::string.

We then iterate over the map using a range-based for loop, and print the key and corresponding value of each pair.

Conclusion

Using an initializer list to create a std::map in C++11 is a simple and effective way of initializing a map with a list of key-value pairs. It makes the code more concise and readable.