C++ 向量::_M_range_check 错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18796782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:13:04  来源:igfitidea点击:

C++ vector::_M_range_check Error?

c++vectoroutofrangeexception

提问by Mark S.

Here's my function:

这是我的功能:

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

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:

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

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.

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

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.

前任。将第一行的内容存入 file.at(0) 将第二行的内容存入 file.at(1) 以此类推,直到文本文件中没有更多行为止。

The Error:

错误:

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

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

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

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

Thanks in advance for your help.

在此先感谢您的帮助。

回答by billz

vector fileis empty, file.at(x)will throw out of range exception. You need std::vector::push_backhere:

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

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

回答by ChronoTrigger

file.at(x)accesses the element at the x-th position, but this must exists, it is not automatically created if it is not present. To add elements to your vector, you must use push_backor insert. For example:

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