Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would a std::map extended initializer list look like?

People also ask

What is STD initializer list in C++?

std::initializer_listThis type is used to access the values in a C++ initialization list, which is a list of elements of type const T . Notice though that this template class is not implicitly defined and the header <initializer_list> shall be included to access it, even if the type is used implicitly.

What is std::map in C++?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.

Are std::map keys sorted?

std::map is a key-value container that maintains its keys in sorted order at all times. Generally std::map is implemented as a tree of key-value pairs, and not a hash map.


It exists and works well:

std::map <int, std::string>  x
  {
    std::make_pair (42, "foo"),
    std::make_pair (3, "bar")
  };

Remember that value type of a map is pair <const key_type, mapped_type>, so you basically need a list of pairs with of the same or convertible types.

With unified initialization with std::pair, the code becomes even simpler

std::map <int, std::string> x { 
  { 42, "foo" }, 
  { 3, "bar" } 
};

I'd like to add to doublep's answer that list initialization also works for nested maps. For example, if you have a std::map with std::map values, then you can initialize it in the following way (just make sure you don't drown in curly braces):

int main() {
    std::map<int, std::map<std::string, double>> myMap{
        {1, {{"a", 1.0}, {"b", 2.0}}}, {3, {{"c", 3.0}, {"d", 4.0}, {"e", 5.0}}}
    };

    // C++17: Range-based for loops with structured binding.
    for (auto const &[k1, v1] : myMap) {
        std::cout << k1 << " =>";
        for (auto const &[k2, v2] : v1)            
            std::cout << " " << k2 << "->" << v2;
        std::cout << std::endl;
    }

    return 0;
}

Output:

1 => a->1 b->2
3 => c->3 d->4 e->5

Code on Coliru