簡體   English   中英

向量 <string> push_back崩潰

[英]vector<string> push_back crash

我的第一個動機是使用“ 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很大。 有人可以幫我嗎? 非常感謝。

使用此代碼,您的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);
}

也許試試這個:

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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM