C++ 向量::_M_range_check 错误? [英] C++ vector::_M_range_check Error?

查看:26
本文介绍了C++ 向量::_M_range_check 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的功能:

void loadfromfile(string fn, vector<string>& file){
    int x = 0;
    ifstream text(fn.c_str());
    while(text.good()){
        getline(text, file.at(x));
        x++;
    }
    //cout << fn << endl;
}    

我传入的 fn 的值只是一个文本文件的名称 ('10a.txt')我传入的文件的值声明如下:

The value of fn that I'm passing in is just the name of a text file ('10a.txt') The value of file that I'm passing in is declared as follows:

vector<string> file1;

我没有定义大小的原因是因为我认为我不必使用向量,它们是动态的......不是吗?

The reason I didn't define a size is because I didn't think I had to with vectors, they're dynamic... aren't they?

这个函数应该读取给定的文本文件并将每一行的全部内容存储到一个向量单元格中.

This function is supposed to read a given text file and store the full contents of each line into a single vector cell.

例如.将第一行的内容存储到 file.at(0) 中将第二行的内容存入 file.at(1)依此类推,直到文本文件中不再有任何行.

Ex. Store the contents of first line into file.at(0) Store the contents of the second line into file.at(1) And so on, until there aren't any more lines in the text file.

错误:

在抛出 'std::out_of_range' 实例后调用终止what(): 向量::_M_range_check

terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check

我认为while循环中的检查应该可以防止这个错误!

I thought the check in the while loop should prevent this error!

预先感谢您的帮助.

推荐答案

vector file 为空,file.at(x) 会抛出超出范围的异常.您需要 std::vector::push_back 在这里:

vector file is empty, file.at(x) will throw out of range exception. You need std::vector::push_back here:

std::string line;
while(std::getline(text, line))
{
    file.push_back(line);
}

或者您可以简单地从文件构造字符串向量:

Or you could simply construct vector of string from file:

std::vector<std::string> lines((std::istream_iterator<std::string>(fn.c_str())),
                                std::istream_iterator<std::string>());

这篇关于C++ 向量::_M_range_check 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆