【问题标题】:Parse a file and store it in a class解析文件并将其存储在一个类中
【发布时间】: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-&gt;first; person.address = it-&gt;second;
  • Class 并不是最好的解决方案。考虑使用map。它会更合适。
  • map 仅在密钥唯一的情况下才有效。

标签: c++ vector hash


【解决方案1】:

如果你有

std::vector<test> tests;

你可以换行

getlist.push_back(make_pair(test,test2));

tests.emplace_back(test, test2); // since c++11

BTW Class 必须小写:class。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2012-05-19
    • 2015-07-16
    • 1970-01-01
    相关资源
    最近更新 更多