首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >vector<string> push_back坠机

vector<string> push_back坠机
EN

Stack Overflow用户
提问于 2015-04-17 03:38:28
回答 1查看 1.1K关注 0票数 0

我的第一个动机是像这样使用"vector< set >“:

代码语言:javascript
运行
复制
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)
}

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

代码语言:javascript
运行
复制
ifstream fin(file);
string line;
vector<string> diag;
while(getline(fin, line))
    diag.push_back(line);

这个程序在读某一行时会突然崩溃。另外,这个文件很大,大约是4G。有人能帮我吗?非常感谢。

EN

回答 1

Stack Overflow用户

发布于 2015-04-17 03:51:12

使用这里的代码,您的temp_set就会变得越来越大,因为它不会在行之间被清空:

代码语言:javascript
运行
复制
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);
}

不妨试试这个:

代码语言:javascript
运行
复制
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,您可以更高效地这样做:

代码语言:javascript
运行
复制
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());
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29689818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档