为什么这段代码运行,VC++ 会显示超出范围的异常?
错误消息:向量行:933 表达式:“标准 C++ 库超出范围”& & 0
high 是一个返回迭代器中最高元素的函数。然后我构造了一个数组和一个向量,使用 high 来找到其中的最高元素。
这是迭代器.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;
}
}