gpt4 book ai didi

c++ - 构建多级字典 : a python to c++ translation

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:56:34 24 4
gpt4 key购买 nike

我试图在 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;

}

最佳答案

遍历容器就像从 begin() 迭代到 end() 一样简单。容器的类型通过添加::iterator或::const_iterator来提供迭代器类型。

这是一个完整的例子。我试着坚持你的代码。请注意有关 C++11 中新语法的注释。

#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;
field="Abcd ";
lis.push_back("Tom");
lis.push_back("Eve");
MultiDict[field]=lis;
// This works in C++11 :
MultiDict["Efgh "]={"Joe","Lisa"};

}

void MultiLevDict::Display() const
{
for(map<string,list<string> >::const_iterator it=MultiDict.begin();
it!=MultiDict.end();++it){
std::cout << "key: was: "<<it->first<<std::endl;
for (list<string>::const_iterator it2=it->second.begin();
it2!=it->second.end();++it2){
std::cout << " "<<it->first<< " contains " <<*it2<<std::endl;
}
}
}

int main() {
MultiLevDict myd;
myd.Setter();
myd.Display();
}

结果是

key: was: Abcd 
Abcd contains Tom
Abcd contains Eve
key: was: Efgh
Efgh contains Joe
Efgh contains Lisa

关于c++ - 构建多级字典 : a python to c++ translation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8979193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com