【问题标题】:C++: Unhandled exception: std::out_of_range at memory locationC++:未处理的异常:内存位置的 std::out_of_range
【发布时间】:2021-02-09 18:54:56
【问题描述】:

目前正在学习 C++ 构建一个小程序,该程序接受电影名称,将它们存储在一个向量中,然后根据用户输入输出它。问题是我做了一个显示电影列表的功能。现在每次运行该函数时都会出现此错误:

ConsoleApplication2.exe 中 0x769DA842 处的未处理异常:Microsoft C++ 异常:内存位置 0x0113F674 处的 std::out_of_range。

代码如下:

#include <iostream>
#include <vector>

std::vector <std::string> movieList;
std::vector <int>::iterator it;

void AddMovie(std::string movie)
{
    movieList.push_back(movie);
}

void DeleteMovie(int i)
{
    movieList.erase(movieList.begin() + i - 1);
}

void ShowMovies()
{
    for (int i = 0; movieList.size() > 1; i++)
    {
        std::cout << movieList.at(i) << std::endl;
    }
}

int main()
{

    int i{ 0 };

    movieList.push_back("Inception");
    movieList.push_back("Peter Pan");
    movieList.push_back("Jaws");

    std::cout << "Delete movie: ";
    std::cin >> i;
    DeleteMovie(i);
    ShowMovies();

    
}

错误在行中断

std::cout

【问题讨论】:

  • 如果列表中至少有 2 个项目,for (int i = 0; movieList.size() &gt; 1; i++) 将永远持续下去。你的意思可能是for (int i = 0; i &lt; movieList.size(); i++)
  • 非常有帮助!谢谢你纠正我的逻辑:)

标签: c++ c++14


【解决方案1】:

在 for 循环中,条件 movieList.size() > 1 始终为真(如果列表中有多个电影),因此您将 i 递增到超出列表,访问超出向量范围的内存。

这个例子应该可以工作,因为变量 i 只在循环体中使用,直到它达到 movieList.size() - 1 (正如@user4581301 上面评论的那样,它被增加到movieList .size(),但循环体中没有使用最后一个值):

void ShowMovies()
{
    for (int i = 0; i < movieList.size(); i++)
    {
        std::cout << movieList.at(i) << std::endl;
    }
}

【讨论】:

  • 替代:for (const auto &amp; val: movieList) {std::cout &lt;&lt; val &lt;&lt; std::endl; }Documentation on range-based for
  • 小修正:变量 i 只增加直到它达到 movieList.size() - 1: 并不完全正确。 i 递增到 movieList.size(),但 i 到达 movieList.size() 是退出条件,因此循环体中不使用 movieList.size() - 1i 在到达 movieList.size() 后立即超出范围,所以这一点没有实际意义。
  • @user4581301 你是对的,它比我说的增加了一次,但没有在循环中使用。
猜你喜欢
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 2013-12-20
  • 1970-01-01
  • 2016-09-23
相关资源
最近更新 更多