std :: map扩展初始化列表会是什么样的?

时间:2010-07-14 20:19:47

标签: c++ c++11 dictionary initializer-list

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

我已经尝试了一些组合......好吧,我能用GCC 4.4想到的一切,但没有发现任何编译过的。

2 个答案:

答案 0 :(得分:130)

它存在且运作良好:

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

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

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

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

答案 1 :(得分:0)

我想向doublep's answer添加list initialization也适用于嵌套地图。例如,如果您有一个带有std::map值的std::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;
}

输出:

  

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

Code on Coliru