tags:

views:

71

answers:

3

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?

+3  A: 

No.

Not with the current standard (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.

Klaim
+1. The next standard even allows `map<int, Bar> m { { 0, { 1, 2} } };`
Johannes Schaub - litb
Johannes> Didn't even think about this possibility, thanks ***ç*** . We'll get in initialization paradize. :D
Klaim
+5  A: 

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);
Martin York
A: 

Works fine for me.

using: gcc version 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:

warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x

Adding that switch and -Wall compiled fine. Maybe upgrade your compiler?