灵感来自 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/