【问题标题】:Using Initializer Lists with std::map使用带有 std::map 的初始化列表
【发布时间】:2016-02-06 19:14:19
【问题描述】:

我问了一个earlier question,它在 CString 和 Unicode 问题上跑题了。
我现在已将示例简化为 namespace stdcout(而不是 printf)。
但核心问题依然存在。

这与question nominated as a duplicate 相关,但独立于question nominated as a duplicate。 该问题与地图中的地图有关,并且已有 2 年多的历史了,并指出该问题是编译器团队的优先事项。 (显然这不是优先事项)
这个问题值得保持开放

我是否正确使用了初始化程序?
有没有什么简单的方法可以在没有主要解决方法的情况下解决这个问题?
(这是一个基于更复杂程序的最小示例)

#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" 幸存。

在我看来,std::map 的初始化器列表真的被破坏了。

我正在使用带有 Unicode 的 Microsoft Visual Studio 2013。
这发生在 DebugRelease 构建中,Optimizations Disabled/O2 相同的代码在 IDEOne

上运行良好

【问题讨论】:

  • 您可以添加您拥有的编译选项,即优化级别、调试/节点错误等
  • 您是否尝试为结构显式提供 ctor?禁用移动 ctor?
  • Am I using the Initializers properly? 我想是的,因为你的代码在 VS2015 上对我来说很好,无论是 unicode 还是 Ascii。问题一定出在其他地方。
  • @abelenky 最近我不得不使用 VS2008!

标签: c++ visual-studio c++11 visual-studio-2013


【解决方案1】:

Slava 的坚持下,我与 ctors 一起找到了一个简单的解决方法:

#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 承认的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多