在C ++中将结构数据保存到地图中

时间:2013-09-06 20:46:59

标签: c++ map struct

如何在没有首先创建和定义具有struct类型的实际对象的情况下,如何将数据添加到包含int键的映射和作为struct的值?基本上我有:

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.

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您使用的是C ++ 11,则此代码已经在运行:

#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;
}

编译:

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

如果你没有,那么你运气不好,但所有主要的编译器应该支持c ++ 11初始化 - 确保你得到最新的版本。