如何创建一个数组,使用户知道他们是越野的

How to create a array that lets user know they are out-of-bounds?

本文关键字:用户 他们是 数组 创建 何创建 一个      更新时间:2023-10-16

我正在尝试创建一个程序,该程序可以帮助用户创建从任何整数开始的数组索引。它还应在执行/访问距离的数组组件期间通知用户。

这就是我到目前为止的。

#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 (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 for Dynamic" arrays"或std :: dramay for固定大小数组。

std :: Array在所有主要编译器上的开销为零,并且在C数组周围或多或少是C 包装器。

为了让用户知道何时何时超出范围,大多数标准容器都提供at(std::size_t n)方法(例如STD :: vector :: at),这些方法可以为您检查所有的愤怒并投入std :: out_of_range exception提供无效的索引/位置时。

您现在要做的就是捕获该异常,并在您愿意的情况下打印一条消息。这是一个小例子:

#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';
    }
}

实时预览-IdeOne.com

相关文章: