0

How would I add data to map containing an int key and a value that is a struct without first creating and defining an actual object with the struct type? Basically I have:

struct myStruct { string name2; int aCnt; std::list<string> theItems; };

// Now I define a map
std::map<string, myStruct> myMap;

// Now I want to add items to myMap.  
mymap["ONE"] = {"TEN", 3, {"p1","p2","p3"}};  // But this doesn't seem to work

// I know I could do something like
myStruct myst;
myst.name2 = "TEN";
myst.aCnt = 3;
...blah blah

mymap["ONE"] = myst;

// But I don't want to have to write all of those lines especially because
// this is being done as an initialization of the map.

Thanks!

GregH
  • 12,278
  • 23
  • 73
  • 109
  • Let's ask are you *really* ? =P After fixing the plethora of typos this works in C++11 [(See it live)](http://ideone.com/a97JRX) – WhozCraig Sep 06 '13 at 21:12
  • Actually, no I'm not working in C++11. I'm fairly new to C++, sorry. – GregH Sep 06 '13 at 21:19

1 Answers1

0

If you are using C++11, this code is already working:

#include <iostream>
#include <map>
#include <string>
#include <list>
using namespace std;


struct myStruct { string name2; int aCnt; std::list<string> theItems; };
int main()
{

        // Now I define a map
        std::map<string, myStruct> myMap;

        // Now I want to add items to myMap.
        myMap["ONE"] = {"TEN", 3, {"p1","p2","p3"}};  // But this doesn't seem to work





        return 0;
}

And compile:

burgos@germany:~/test$ g++ struct.cpp -o struct -std=c++11
burgos@germany:~/test$

If you don't then you're out of luck, but all major compilers should support c++11 initialization - make sure you get the latest version.

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
  • Yeah, I tried using the c++11 option but apparently it doesn't work. My environment must not support it. Is there another way to do it not under C++11? – GregH Sep 06 '13 at 21:22
  • @GregH, see http://stackoverflow.com/questions/138600/ for an example of Nemanja sugestion. – mMontu Nov 22 '13 at 11:18