【发布时间】:2019-01-16 09:09:49
【问题描述】:
我想知道当不同的文件存储在字符串向量映射中时如何管理内存。 我试图读取每个 10 个月的不同文件以将它们放入内存中,当我使用 KSySGuard 检查内存时,出现的内存是我文件内存的两倍多(约 70 个月)。 我给你一个代码示例: 有一个函数readfile():
std::vector<std::string> read_file(std::string& path){
ifstream fichier(path);
std::vector<std::string> fich;
if(fichier){
string ligne;
while(getline(fichier, ligne)){
fich.push_back(ligne);
}
}
fichier.close();
return fich;
}
这个函数在另一个正在构建我的地图中使用:
std::map<std::string, std::vector<std::string>> buildmap(std::string folder){
std::map<std::string,std::vector<std::string>> evaluations; std::vector<std::string> vecFiles = {"file1","file2","file3"};
for( auto i = 0; i < vecFiles.size(); i++ )
{
std::stringstream strad;
strad <<vecFiles[i] ;
std::string path(folder+vecFiles[i]);
std::vector<std::string> a = read_file(path);
evaluations[strad.str()]=a;
}
return evaluations;
}
所以,我不明白为什么内存与文件大小相比如此之高。有没有更有效的方法来构建这种容器?
【问题讨论】:
-
与您的问题完全无关,但为什么字符串流
strad?为什么不直接使用vecFile[i]?您甚至不需要path变量(如果您让read_file取而代之的是const引用,那么您确实应该这样做)。 -
std::vector<std::string> a = read_file(path); evaluations[strad.str()]=a;这是一个副本,你可以移动它(实际上你使用移动插入代替)。 -
一摞纸在抽屉里不会占用太多空间,但要找到你想要的那张却非常慢。为有效定位而整理的一堆文件将占用更多空间。
-
A
std::string会有一些开销。文件中的很多行意味着很多std::strings 和更多开销。您应该可以通过使用std::vector<char>来减少一些开销,但我不太确定这是您想要做的事情。
标签: c++ vector memory-management stdmap