为什么这会超出范围异常

时间:2012-10-17 00:19:58

标签: c++ vector outofrangeexception

为什么这段代码会运行,VC ++会显示超出范围的异常?

错误讯息: 矢量线:933 表达式:“标准C ++库超出范围”& &安培; 0

high是一个返回迭代器中最高元素的函数。然后我构造一个数组和一个向量,用high来找到它们中的最高元素。

这是iterator.h:

template<class Iterator> Iterator high(Iterator first, Iterator last)
{
    Iterator high = first;
    for(Iterator p = first; p != last; ++p)
        if(*high < *p) high = p;
    return high;
}

这是主要功能:

#include <iostream>
#include <vector>
#include "iterator.h"

using namespace std;

double* get_from_jack(int* count)
{
    double* p = new double[5];
    p[0] = 2.3;
    p[1] = 3.1;
    p[2] = 2.1;
    p[3] = 1.2;
    p[4] = 4.3;
    *count = 5;
    return p;
}

vector<double>* get_from_jill()
{
    vector<double> v;
    v.push_back(2.1);
    v.push_back(3.8);
    v.push_back(5.1);
    v.push_back(2.2);
    v.push_back(1.9);
    v.push_back(4.4);
    vector<double>* p = &v;
    return p;
}

void fct()
{
    int jack_count = 0;
    double* jack_data = get_from_jack(&jack_count);
    vector<double>* jill_data = get_from_jill();

    double* jack_high = high(jack_data, jack_data+jack_count);
    vector<double>& v = *jill_data;
    double* jill_high = high( &v[0], &v[0]+v.size() );

    cout << "Jill's high " << *jill_high << "; Jack's high " << *jack_high;

    delete[] jack_data;
    delete jill_data;
    //delete jack_high;
    //delete jill_high;
}

int main()
{
    try{
        fct();
        int n;
        cin >> n;
        return 0;
    }
    catch(exception&e)
    {
        cerr << e.what();
        return 1;
    }
    catch(...)
    {
        return 2;
    }
}

1 个答案:

答案 0 :(得分:1)

get_from_jill()向指针返回一个向量,该指针在函数终止后不再存在。 您必须像对数组一样在堆上实例化向量,或者返回它的副本。我更喜欢后者,它会使你的代码更简洁。