简体   繁体   English

C ++:结构初始化和映射

[英]C++: Struct initialization and maps

This works fine: 这工作正常:

#include <iostream>
#include <map>

using namespace std;

struct Bar
{
    int i;
    int f;
};

int main()
    {
        map<int, Bar> m;

    Bar b;
    b.i = 1;
    b.f = 2;
    m[0] = b;
}

But if I want to make it a little more concise, I get errors: 但是,如果我想使其更简洁一些,则会出现错误:

int main()
{
    map<int, Bar> m;

    m[0] = {1, 2};
}

Is there any way to make that struct initialization syntax work? 有什么方法可以使该结构初始化语法起作用? Am I doing it wrong, or is it prohibited for maps? 我做错了吗,还是地图禁止使用?

You can add a constructor: 您可以添加一个构造函数:
In this situation I would say it is better than the fancy new initializer as it actually lets the maintainer see what type is being put in the map without having to go and look for it. 在这种情况下,我会说它比花哨的新初始化程序好,因为它实际上可以让维护者查看映射中正在放置的类型,而不必去寻找它。

struct Bar
{
    Bar(int anI,int aJ)
      :i(anI), j(aJ)
    {}
    int i;
    int j;
}

.....

m[0] = Bar(1,2);

No. 没有。

Not with the current standard (C++03). 不适用于当前标准(C ++ 03)。

But if you're using a compiler having the new initialization syntax of C++0x implemented ( like a recent version of gcc ), then it's allowed to do that. 但是,如果您使用的编译器实现了C ++ 0x新初始化语法例如gcc的最新版本 ),则可以这样做。

Works fine for me. 对我来说很好。

using: gcc version 4.4.4 20100503 (Red Hat 4.4.4-2) (GCC) 使用:gcc版本4.4.4 20100503(Red Hat 4.4.4-2)(GCC)

The latter syntax throws warnings but still compiles, apparently this is c++0x syntax: 后一种语法会发出警告,但仍会编译,显然这是c ++ 0x语法:

warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x 警告:扩展的初始化程序列表仅适用于-std = c ++ 0x或-std = gnu ++ 0x

Adding that switch and -Wall compiled fine. 添加该开关和-Wall编译正常。 Maybe upgrade your compiler? 也许升级您的编译器?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM