c++ - 运行非常简单的程序 (C++) 时出现运行时错误

标签 c++ vector stl runtime-error

<分区>

作为学习练习的一部分,我编写了一个程序,该程序将 double 作为输入,并输出所有 double 的总和,以及最小值、最大值和平均值。尝试运行该程序时,出现此运行时错误:

 Unhandled exception at 0x74b01d4d in Hello World.exe: Microsoft C++ exception: Range_error at memory location 0x00dcf760.

当我使用 Visual Studio 2010 调试选项时,我得到 vector subscript is out of range

代码是:

#include "C:\Users\Kevin\Documents\Visual Studio 2010\Projects\std_lib_facilities.h"

int main() {
    vector<double> v;
    double number = 0;
    cout << "Enter the distance between two cities along the route.\n";
    while (cin >> number) {
        double sum = 0;
        v.push_back(number);
        sort(v.begin(),v.end());
        for (size_t i = 0; i < v.size(); ++i)
            sum += v[i];
        cout << "The total distance from each city is " << sum 
                     << ". The smallest distance is " << v[0] 
                     << " and the greatest distance is " << v[v.size()] 
                     <<". The mean distance is " << sum/v.size() <<".\n";
        cout << "Enter the distance between two cities along the route.\n";}
}

我不得不更改 for 循环中定义的变量类型,因为我遇到了有符号/无符号不匹配错误。代码在编译时没有给出错误,我很难看到问题所在。

最佳答案

" and the greatest distance is " << v[v.size()]

是一个未定义的行为,因为 vector 中的最后一个索引是 v.size() - 1 if v.size() > 0 (如果 v.size() = 0 没有项目也没有下标)

你应该这样写:

if( !v.empty())
    std::cout << " and the greatest distance is " << v[ v.size() - 1];

或更好;

if ( !v.empty()) {
    std::cout << " and the greatest distance is " << v.back();

std::vector::back

关于c++ - 运行非常简单的程序 (C++) 时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23874629/

相关文章:

C++ 比较器对结构 vector 进行无效排序

c++ - 计时 STL 容器 - 广泛的变化?

c++ - 我们可以在一条语句中拆分、操作和重新连接 C++ 中的字符串吗?

c++ - FBString 的小字符串优化是否依赖未定义行为?

c++ - 为什么这个 dynamic_cast<T> 不起作用?

c++ - 模板内的模板 : why "` >>' should be ` > >' within a nested template argument list"

sorting - 使用动态改变其行为的比较器对向量进行排序

c++ - 为什么 lower_bound 和 upper_bound 的谓词版本不一致地传递迭代器值?

C++ (g++) 编译错误,预期为 "="/etc。 'MyWindow"(我的类(class)名称)之前

c++ - boost::variant 隐式转换为字符串