为什么这会导致超出范围的异常
Why this can course an out of range exception
为什么运行此代码,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;
}
}
get_from_jill()
将向量返回到一个指针,一旦函数终止,该指针就不再存在。您要么必须像使用数组一样实例化堆上的向量,要么返回它的副本。我更喜欢后者,它会使您的代码更简洁。
相关文章:
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- C++矢量超出范围异常
- 张量不会在超出范围索引时引发异常
- 如果一个对象是在本地创建的,并在C++中作为异常抛出,那么本地对象如何在其范围之外有效,即在 catch 块中?
- basic_string::替换的超出范围异常,而在范围内,正如调试相同参数的输出所证明的那样
- 当数字可能超出C++中特定数据类型的范围时如何处理异常?
- 程序崩溃,说向量不超出范围异常
- Windows 错误报告和超出范围的异常
- 对象在超出范围时是否被销毁,因为它们已引发异常.C++
- 从覆盖范围报告中删除自动生成的异常代码
- C++ 超出范围异常
- 为什么在 std::vector 中使用索引超出范围的运算符 [] 时没有出现异常?
- 为什么这会导致超出范围的异常
- 用于处理超出范围错误的异常类 - C++
- 当传递表示负值的十六进制时,C++stoll抛出超出范围的异常
- 字符串长度为10或更长的c++stol抛出范围外异常
- C++:如果抛出异常,那么超出范围的对象将被销毁
- 给定范围内的完美平方:循环执行异常
- 通过引用捕获(使用 catch)时异常对象的范围