问题描述
我问了一个之前的问题,这在 CString 和 Unicode 问题中偏离了主题.
我现在将我的示例简化为 namespace std
和 cout
(而不是 printf
).
但核心问题依然存在.
I asked an earlier question, which got off-topic in CString and Unicode issues.
I've now reduced my example to namespace std
and cout
(instead of printf
).
But the core problem still remains.
这与 被提名为重复的问题.这个问题是关于地图中的地图,并且已经超过 2 年了,并指出该问题是编译器团队的优先事项.(显然这不是一个优先事项)
这个问题值得悬而未决
This is related to, but separate from the question nominated as a duplicate.
That question is about maps-in-maps, and is over 2 years old, with the note that the issue is a priority for the compiler team. (Clearly it is not a priority)
This question is worthy of staying open
我是否正确使用了初始化程序?
有没有什么简单的方法可以在没有主要解决方法的情况下解决这个问题?
(这是一个基于更复杂程序的最小示例)
Am I using the Initializers properly?
Is there any simple way to fix this without a major workaround?
(This is a minimal example based on a much more complex program)
#include <map>
#include <string>
#include <iostream>
struct Params
{
int inputType;
std::string moduleName;
};
int main()
{
std::map<std::string, Params> options{
{ "Add", { 30, "RecordLib" } },
{ "Open", { 40, "ViewLib" } },
{ "Close", { 50, "EditLib" } },
{ "Inventory", { 60, "ControlLib"} },
{ "Report", { 70, "ReportLib" } }
};
for (const auto& pair : options)
{
std::cout << "Entry: " << pair.first << " ==> { " << pair.second.moduleName << " }" << std::endl;
}
return 0;
}
输出
Entry: ==> { }
Entry: Report ==> { }
您只能看到幸存下来的最后一个字符串 "Report"
.
You can see only the final string "Report"
survived.
在我看来,std::map
的初始化列表真的坏了.
It really looks to me like the intializer list for std::map
is just broken.
我使用的是带有 Unicode 的 Microsoft Visual Studio 2013.
这发生在 Debug
和 Release
构建中,Optimizations Disabled
或 /O2
相同的代码在 IDEOne
I'm using Microsoft Visual Studio 2013, with Unicode.
This happens in both Debug
and Release
builds, with Optimizations Disabled
or /O2
The same code works fine on IDEOne
推荐答案
在 Slava 的坚持下,我与ctors 找到一个简单的解决方法:
At Slava's insistence, I worked with ctors to find an easy fix:
#include <map>
#include <string>
#include <iostream>
struct Params
{
int inputType;
std::string moduleName;
Params(const int n, const std::string& s) :
inputType(n),
moduleName(s)
{ }
};
int main()
{
std::map<std::string, Params> options = {
{ "Add", Params(30, "RecordLib" ) },
{ "Open", Params(40, "ViewLib" ) },
{ "Close", Params(50, "EditLib" ) },
{ "Inventory", Params(60, "ControlLib") },
{ "Report", Params(70, "ReportLib" ) }
};
for (const auto& pair : options)
{
std::cout << "Entry: " << pair.first << " ==> { " << pair.second.moduleName << " }" << std::endl;
}
return 0;
}
但是,原始代码应该可以工作,并且显然是 Microsoft 承认的错误.
However, the original code should have worked, and apparently is an acknowledged bug by Microsoft.
这篇关于将初始化列表与 std::map 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!