C++ std::map 扩展初始值设定项列表会是什么样子?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3250123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:26:30  来源:igfitidea点击:

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

c++c++11dictionaryinitializer-list

提问by rubenvb

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

如果它甚至存在,std::map扩展的初始化列表会是什么样子?

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

我已经尝试了一些......好吧,我能想到的 GCC 4.4 的所有组合,但没有发现任何可以编译的内容。

回答by doublep

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.

请记住,映射的值类型是pair <const key_type, mapped_type>,因此您基本上需要具有相同或可转换类型的对列表。

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

使用 std::pair 统一初始化,代码变得更加简单

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

回答by honk

I'd like to add to doublep's answerthat list initializationalso works for nested maps. For example, if you have a std::mapwith std::mapvalues, then you can initialize it in the following way (just make sure you don't drown in curly braces):

我想添加到doublep 的答案中列表初始化也适用于嵌套地图。例如,如果你有一个std::mapwithstd::map值,那么你可以通过以下方式初始化它(只要确保你没有被花括号淹没):

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

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

Code on Coliru

Coliru 上的代码