【发布时间】:2018-01-01 05:12:31
【问题描述】:
while(!myfilename.eof()){
getline( myfilename , linelist );
linelist2 = linelist.substr(0,linelist.find(";")); //skips line after ';'
if(linelist2.find_first_not_of("#")){} //removes lines starts with #
else{
size_t pos = linelist2.find("=");
test = linelist2.substr(0,pos);
test2 = linelist2.substr(pos+1);
getlist.push_back(make_pair(test,test2));
}
}
//iterator
/*for(std::vector <std::pair<std::string,std::string>>::iterator it=getlist.begin(); it!=getlist.end();it++)
{
std::cout << it->first << "=>" << it->second << "\n";
}*/
myfilename.close();
我解析了文件并存储在一个向量中。但我的实际工作是解析文件并将其存储在一个类中。 例如:
class test{
string Name;
string address;
};
现在文本文件可以有
Name = tom
address = verger
我应该如何将它存储在班级成员中。那就是从向量到类?
向量可以有
Name=> tom
address=> verger
【问题讨论】:
-
为什么不直接赋值呢?例如。在迭代中,您注释掉了
test person; person.Name = it->first; person.address = it->second;。 -
Class 并不是最好的解决方案。考虑使用
map。它会更合适。 -
map仅在密钥唯一的情况下才有效。