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

时间:2014-05-26 16:50:50

标签: c++ vector stl runtime-error

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

 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循环中定义的变量的类型,因为我收到了签名/未签名的不匹配错误。编译时代码没有错误,我很难看到问题。

1 个答案:

答案 0 :(得分:3)

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

是一个未定义的行为,因为如果v.size() - 1(如果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