受此答案的启发,我尝试了下一个示例:
#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"},
};
但是为什么在上面的例子中编译失败了?