如何创建一个让用户知道他们超出界限的数组?

时间:2017-03-03 03:00:36

标签: c++ arrays int

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

这是我到目前为止所做的。

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

2 个答案:

答案 0 :(得分:0)

您的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 == capacity时边缘情况会发生什么?您的代码根本不处理这种情况。

为了使这个更整洁,你可以用一个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;
};

答案 1 :(得分:0)

您可以使用标准容器(例如std::vector)来处理动态&#34;数组&#34;而不是处理内存管理。或std::array用于固定大小的数组。

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

为了让用户知道索引何时超出范围,大多数标准容器都提供了at(std::size_t n)方法(例如std::vector::at),它为你做了所有的愤怒检查并抛出{{3提供无效的索引/位置时出现异常。

现在你所要做的就是抓住那个例外并打印一条消息。 这是一个小例子:

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

std::out_of_range