构建多级字典:从 python 到 c++翻译
我正在尝试用 C++ 模仿 python 字典。例如,我想构建一些东西,比如
{"The Dark Night Rises": {"year": 2012, "StoryLine": "this is the story.....", "Genres": ["action","crime","Thriller"]}}
我正在使用 STL 映射和列表来构建这种字典。但我不确定如何使用迭代器。有人可以帮我举一个构建上述字典的例子吗?我开始像下面这样构建一个简单的字典,例如 {"cast":["action","crime","Thriller"]}
。我很困惑如何构建上述多级字典,并特别对它们进行迭代。
#include<iostream>
#include<string>
#include<map>
#include<iterator>
#include<list>
using namespace std;
class MultiLevDict
{
private:
list<string> lis;
map<string,list<string> > MultiDict;
public:
void Setter();
void Display() const;
};
void MultiLevDict::Setter()
{
string field;
string cast;
int sizeCast;
cout<<"enter the field of the movie:";
cin>>field;
cout<<endl;
cout<<"how many cast are there in this movie?:";
cin>>sizeCast;
for (int i=0; i<sizeCast; i++)
{
cin>>cast;
lis.push_back(cast);
}
MultiDict[field]=lis;
}
void MultiLevDict::Display() const
{
list<string>::iterator lisIt;
}
I'm trying to mimic the python dictionary in C++. For example I want to build something like
{"The Dark Night Rises": {"year": 2012, "StoryLine": "this is the story.....", "Genres": ["action","crime","Thriller"]}}
I'm using the STL map and lists for building up this kind of dictionary. But I'm not sure how to use the iterators. Can some one help me with an example of building the above dictionary. I started something like below to just build a simple dictionary like {"cast":["action","crime","Thriller"]}
. I'm confused how to build the above mentioned multilevel dictionaries, and specially iterating over them.
#include<iostream>
#include<string>
#include<map>
#include<iterator>
#include<list>
using namespace std;
class MultiLevDict
{
private:
list<string> lis;
map<string,list<string> > MultiDict;
public:
void Setter();
void Display() const;
};
void MultiLevDict::Setter()
{
string field;
string cast;
int sizeCast;
cout<<"enter the field of the movie:";
cin>>field;
cout<<endl;
cout<<"how many cast are there in this movie?:";
cin>>sizeCast;
for (int i=0; i<sizeCast; i++)
{
cin>>cast;
lis.push_back(cast);
}
MultiDict[field]=lis;
}
void MultiLevDict::Display() const
{
list<string>::iterator lisIt;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
循环容器就像从 begin() 迭代到 end() 一样简单。迭代器类型由容器的类型通过添加::iterator 或::const_iterator 来提供。
这是一个完整的例子。我试图坚持你的代码。请注意有关 C++11 中新语法的注释。
结果是
Looping over a container is as easy as iterating from begin() to end(). The iterator type is provided by the type of the container by adding ::iterator or ::const_iterator.
Here's a complete example. I tried to stick to your code. Note the comment about the new syntax in C++11.
the result is