首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将结构化数据保存到C++中的地图中

将结构化数据保存到C++中的地图中
EN

Stack Overflow用户
提问于 2013-09-06 20:46:58
回答 1查看 188关注 0票数 0

如何添加数据以映射包含int键和值的结构,而无需首先使用struct类型创建和定义实际对象?基本上我有:

代码语言:javascript
复制
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.

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-06 21:19:49

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

代码语言:javascript
复制
#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;
}

并汇编:

代码语言:javascript
复制
burgos@germany:~/test$ g++ struct.cpp -o struct -std=c++11
burgos@germany:~/test$

如果没有,那么您就倒霉了,但是所有的主要编译器都应该支持c++11初始化--确保您得到了最新版本。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18666325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档