[英]vector<string> push_back crash
My first motivation is to using "vector< set >" like this: 我的第一个动机是使用“ 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)
}
but it crashed, then I use "vector" to debug the code. 但它崩溃了,然后我使用“向量”来调试代码。 But interesting is that, the program also crashed when I tried to push_back each line of string into the vector.
但有趣的是,当我尝试将字符串的每一行推入向量时,程序也崩溃了。 Here is the code that very simple.
这是非常简单的代码。
ifstream fin(file);
string line;
vector<string> diag;
while(getline(fin, line))
diag.push_back(line);
The program will suddenly crashed when reading some line. 读取某些行时,程序将突然崩溃。 In addition, the file is big about 4G.
另外,该文件关于4G很大。 Could anyone help me?
有人可以帮我吗? thanks a lot.
非常感谢。
With this code here your temp_set
just keeps getting bigger and bigger because it does not get emptied between lines: 使用此代码,您的
temp_set
会越来越大,因为它不会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);
}
Maybe try this: 也许试试这个:
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);
}
If you have C++11 you can be even more efficient like this: 如果您拥有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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.