107

If it even exists, what would a std::map extended initializer list look like?

I've tried some combinations of... well, everything I could think of with GCC 4.4, but found nothing that compiled.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
rubenvb
  • 74,642
  • 33
  • 187
  • 332

2 Answers2

169

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" } 
};
fireant
  • 14,080
  • 4
  • 39
  • 48
  • 4
    Awesome, this makes it very nice stylewise. I might just "drop" support for MSVC 2010 to be able to use this with GCC :). – rubenvb Jul 15 '10 at 08:40
  • 1
    Make sure your compiler supports *Modern C++*, because `map( std::initializer_list init, const Compare& comp = Compare(), const Allocator& alloc = Allocator() );` is available since **C++11**, and `map( std::initializer_list init, const Allocator& );` is only available since **C++14**. Reference: [std::map](https://zh.cppreference.com/w/cpp/container/map) – KaiserKatze Jan 25 '20 at 03:44
6

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

honk
  • 9,137
  • 11
  • 75
  • 83