[英]How to create a array that lets user know they are out-of-bounds?
我正在尝试创建一个程序来帮助用户创建以任何整数开头的数组索引。 它还应该在执行/访问越界的数组组件期间通知用户。
到目前为止,这就是我所拥有的。
#include <iostream>
using namespace std;
int main(){
class safeArray;
};
const int CAPACITY=5;
我已将阵列的容量设置为5,因此可能会有限制。 让用户能够超越界限。
class safeArray() {
userArray= new int [CAPACITY];
用户将能够为数组中的每个插槽创建一个新的int值。
cout <<"Enter any integers for your safe userArray:";
if (int=0;i<CAPACITY;i++) {
cout<<"You are in-bounds!";
}
else (int=0;i>CAPACITY;i++){
cout<<"You are OUT-OF-BOUNDS!";
cout<<endl;
return 0;
};
我使用if-else语句来检查数组下标吗? 我是C ++的新手,因此任何有关简化错误或方法的澄清都将是有帮助的。 谢谢。
您的if语句应为:
if (i<CAPACITY && i>0) {
cout<<"You are in-bounds!";
}
else if (i>CAPACITY){
cout<<"You are OUT-OF-BOUNDS!";
cout<<endl;
return 0;
};
另外,当i ==容量时,在极端情况下会发生什么? 您的代码根本无法处理这种情况。
为了使这种方法更整洁,您可以仅使用一个if / else语句对其进行格式化
if (i<CAPACITY && i>0) { // Or should this be (i<=CAPACITY)??? depends on whether 0 is an index or not
cout<<"You are in-bounds!";
} else {
cout<<"You are OUT-OF-BOUNDS!";
cout<<endl;
return 0;
};
除了处理内存管理,您可以使用标准容器,例如std :: vector用于动态“数组”,或使用std :: array用于固定大小的数组。
std :: array在所有主要编译器上的开销为零,或多或少是C数组周围的C ++包装器。
为了让用户知道索引何时超出范围,大多数标准容器都提供了at(std::size_t n)
方法(例如std :: vector :: at ),该方法会为您进行所有检查并抛出std提供无效的索引/位置时出现:: out_of_range异常。
您现在要做的就是捕获该异常,并在需要时显示一条消息。 这是一个小例子:
#include <iostream>
#include <array>
int main() {
std::array<int, 12> arr;
try {
std::cout << arr.at(15) << '\n';
} catch (std::out_of_range const &) {
std::cout << "Sorry mate, the index you supplied is out of range!" << '\n';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.