我的第一个动机是像这样使用"vector< set >“:
ifstream fin(file)
string line;
vector< set<string> > diag;
set<string> temp_set;
vector<string> temp_vec;
while(getline(fin, line)
{
temp_vec = split(line, " ");
for(int i = 0;i < temp_vec.size();i ++)
temp_set.insert(temp_vec[i]);
diag.push_back(temp_set)
}
但是它崩溃了,然后我使用“向量”来调试代码。但有趣的是,当我试图将每一行字符串放入向量时,程序也崩溃了。这是非常简单的代码。
ifstream fin(file);
string line;
vector<string> diag;
while(getline(fin, line))
diag.push_back(line);
这个程序在读某一行时会突然崩溃。另外,这个文件很大,大约是4G。有人能帮我吗?非常感谢。
发布于 2015-04-17 03:51:12
使用这里的代码,您的temp_set
就会变得越来越大,因为它不会在行之间被清空:
ifstream fin(file);
string line;
vector< set<string> > diag;
set<string> temp_set;
vector<string> temp_vec;
while(getline(fin, line)
{
temp_vec = split(line, " ");
for(int i = 0;i < temp_vec.size();i ++)
temp_set.insert(temp_vec[i]); // when is this set emptied?
diag.push_back(temp_set);
}
不妨试试这个:
ifstream fin(file);
string line;
vector< set<string> > diag;
vector<string> temp_vec;
while(getline(fin, line)
{
temp_vec = split(line, " ");
// no need for loop
// construct a new set each time
set<string> temp_set(temp_vec.begin(), temp_vec.end());
diag.push_back(temp_set);
}
如果您有C++11,您可以更高效地这样做:
std::ifstream fin(file);
std::string line;
std::vector<std::set<std::string> > diag;
std::vector<std::string> temp_vec;
while(std::getline(fin, line))
{
temp_vec = split(line, " ");
diag.emplace_back(temp_vec.begin(), temp_vec.end());
}
https://stackoverflow.com/questions/29689818
复制相似问题