c++ - 为什么初始化 map 时不能省略大括号?

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

灵感来自 this answer ,我尝试了下一个示例:

#include <map>
#include <string>
#include <iostream>

int main()
{
  const std::map< int, std::string > mapping = {
      1, "ONE",
      2, "TWO",
    };

  const auto it = mapping.find( 1 );
  if ( mapping.end() != it )
  {
    std::cout << it->second << std::endl;
  }
  else
  {
    std::cout << "not found!" << std::endl;
  }
}

编译失败并显示下一条错误消息 (g++ 4.6.1):

gh.cpp:11:5: error: could not convert '{1, "ONE", 2, "TWO"}' from '<brace-enclosed initializer list>' to 'const std::map<int, std::basic_string<char> >'

我知道如何解决它:

  const std::map< int, std::string > mapping = {
      {1, "ONE"},
      {2, "TWO"},
    };

但是为什么在上面的例子中编译失败了?

最佳答案

因为 map 是非聚合的,并且包含非聚合元素 (std::pair<key_type, mapped_type>),所以它需要一个包含初始化器列表的初始化器列表,每对一个。

std::pair<int,int> p0{ 1,2 }; // single pair
std::map<int, int> m { { 1,2 } }; // map with one element
std::map<int, int> m { { 1,2 }, { 3,4} }; // map with two elements

请记住,大括号省略的规则适用于聚合,因此它们不适用于此处。

关于c++ - 为什么初始化 map 时不能省略大括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11742592/

相关文章:

c++ - 如何查看为模板类型参数推导的类型?

c++ - 在球员评分程序中显示低于平均分数

c++ - thread_local std::unique_ptr 释放不调用析构函数

c++ - std::priority_queue 包含我自己的类

c++ - 读取初始化列表中的数据

c++ - 使用#define 创建指针

python - 如何在 cython 中制作从 C struct 到 int 的 C++ 映射?

c++ - 像 typedef 一样使用 decltype

c++ - 为什么 std::flat_set 和 std::flat_map 具有 std::initializer_list 的重载构造函数,而其他容器适配器则没有?

c++ - 令人困惑的声明和初始化程序