【问题标题】:C++ vector::_M_range_check Error?C++ 向量::_M_range_check 错误?
【发布时间】:2013-09-13 23:37:43
【问题描述】:

这是我的功能:

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') 我传入的文件的值声明如下:

vector<string> file1;

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

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

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

错误:

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

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

提前感谢您的帮助。

【问题讨论】:

标签: c++ vector outofrangeexception


【解决方案1】:

vector file 为空,file.at(x) 将抛出超出范围异常。你需要std::vector::push_back这里:

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

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

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

【讨论】:

    【解决方案2】:

    file.at(x) 访问第 x 个位置的元素,但这必须存在,如果不存在则不会自动创建。要将元素添加到向量中,您必须使用push_backinsert。例如:

    file.push_back(std::string()); // add a new blank string
    getline(text, file.back());    // get line and store it in the last element of the vector
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多