gpt4 book ai didi

c++ - vector push_back 崩溃

转载 作者:行者123 更新时间:2023-11-28 06:18:50 25 4
gpt4 key购买 nike

我的第一个动机是像这样使用“vector ”:

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

但是它崩溃了,然后我使用“vector”来调试代码。但有趣的是,当我试图将每行字符串 push_back 到 vector 中时,程序也崩溃了。这是非常简单的代码。

ifstream fin(file);
string line;
vector<string> diag;
while(getline(fin, line))
diag.push_back(line);

程序在读取某行时会突然崩溃。另外,文件大了4G左右。谁能帮帮我?非常感谢。

最佳答案

这里使用这段代码,您的 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());
}

关于c++ - vector<string> push_back 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29689818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com