【问题标题】:How to create a array that lets user know they are out-of-bounds?如何创建一个让用户知道他们越界的数组?
【发布时间】:2017-03-03 03:00:36
【问题描述】:

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

这是我目前所拥有的。

#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++ 新手,所以任何关于如何简化它的错误或方法的澄清都会有所帮助。 谢谢。

【问题讨论】:

  • 你很幸运。 C++ 已经有一个带有边界检查的数组对象,它被称为std::vector,如果索引超出范围,它的at() 方法将抛出异常。将其子类化并重载[] 运算符以调用at() 将是一件简单的事情。迄今为止,子类化和运算符重载并不是“C++ 新手”可能学到的东西。所以,继续阅读你的 C++ 书籍,最终你会到达那里。
  • 当您事先知道数组的大小时,最好使用std::array,当索引超出范围时,std::array::at 方法将抛出std::out_of_range
  • 固定大小的 std::array 也有与使用 at() 相同的边界检查。 en.cppreference.com/w/cpp/container/array/at
  • @SamVarshavchik - 不要迂腐,但包装 std::vector 可能会更好。不推荐使用 STL 容器类作为基础,因为 dtor 不是虚拟的。就个人而言,我只是使用香草std::vector 来满足 OP 似乎想要的,但是...... :)

标签: c++ arrays int


【解决方案1】:

你的 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;
};

【讨论】:

  • 负索引值呢?
  • 更好的解决方案是完全禁止使用 unsigned 数据类型的负数。
【解决方案2】:

您可以使用标准容器代替处理内存管理,例如 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';
    }
}

live preview - ideone.com

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多