如何解决错误 'std::out_of_range' what(): _M_range_check ,向量将接受值,直到被告知中断

How to solve the error 'std::out_of_range' what(): _M_range_check , vector will accept values until told to break

本文关键字:range 中断 向量 被告 of 错误 解决 何解决 std out what      更新时间:2023-10-16

嗨,我正在尝试创建一个非常简单的矢量程序来接受整数,然后在提示时,用c++显示最大值。然而,我对此并不熟悉,不可避免地会对此感到恼火。如上所述,它会抛出错误"std::out_of_range"what():_m_range_check,并在提示中断之前接受值。但我不明白为什么,即使浏览了这个论坛很长一段时间。感谢您提前提供的帮助。

#include <iostream>
#include <vector>
using namespace std;
int inputVector (vector<int>);   //prototype functions
void sortVector    (int,vector<int>&files);
void displayVector (vector<int>&files);
int main()
{
    int vectorsize=(0);
    vector <int>files;
    files.reserve(10);
    vectorsize=inputVector (files);
    sortVector (vectorsize, files);
    displayVector (files);
    return 0;
}
void displayVector(vector<int>& files)
{
    cout << " The largest file size is " << files.at(0);
}
int  inputVector(vector<int>files)
{
    int file=0;
    int vectorsize;
    cout << "Enter file sizes  in Megabytes, file size has to be 1 or greater,                                                hit 0 to display max value " << endl;
    do
    {
        cin >> file;
        if (file==0)
        {
            break;
        }
        else
        {
            files.push_back(file) ; //sends value to the vector
            cout << files.size() << endl;
        }
    }
    while (file>0);
    vectorsize=files.size();
    return vectorsize;
}
void sortVector(int vectorsize,vector<int>&files)
{
    int maximum;
    for( int j=0;j<vectorsize;j++)
    {
        for(int i=0;i<(vectorsize-1);i++)
        {
            if(files.at(i)< files.at(i+1))
            {
                maximum=files.at(i);
                files.at(i)=files.at(i+1);
                files.at(i+1)=maximum;
            }
        }
    }
}

inputVector按值获取向量,因此它正在修改副本。改为通过引用传递。此外,您不需要传递矢量大小,因为您只需调用size()即可。

您的vectorsize错误,因此您调用

files.at(i);  // in sortvector()

导致超出范围的错误。实际的矢量大小是0,但您的程序假定了其他内容。这是由于将vector按值传递给函数vectorinput()造成的:在返回该函数时,原始向量没有改变,返回的vectorsize没有意义。

做你想做的事,一个人宁愿

#include <iostream>
#include <vector>
#include <algorithm>
void inputVector (vector<int>&);
int main()
{
  vector<int> files;
  inputVector(files);
  // std::sort(files.begin(),files.end(),std::greater<int>()); // not needed
  std::cout << " The largest file size is "
            << std::max_element(files.begin(),files.end()) << std::endl;
}
void inputVector(vector<int>&files)
{
  std::cout << "Enter file sizes in Megabytes, file size has to be 1 or "
               "greater, enter 0 to display max value " << std::endl;
  files.reserve(10); // not really needed
  while(true) {
    int file;
    std::cin >> file;
    if (file>0) {
      files.push_back(file);
      // std::cout << files.size() << std::endl; // for debugging
    } else
      break;
  }
}

但是,当然,如果您只想找到最大值,就不需要将文件大小存储在向量中。