在C ++中使用有界数组的正确方法是什么?

时间:2016-04-01 16:37:16

标签: c++ arrays

我试图了解 bounded 数组在C ++中是如何工作的。我需要一个快速长度的方法来返回我的有界数组的大小。在Java中,我会做类似的事情:

int[] array = new int[10];

System.out.println(array.length); // 10
System.out.println(array[5]); // 0

array[5] = 11;

System.out.prinltn(array[5]); // 11

如果可能,我想使用对象数组(即实现数组功能的类)而不是指针。我是否正确地说使用对象数组而不是内存指针来处理数组会更自然?

1 个答案:

答案 0 :(得分:2)

C ++有一个类std::array<type, size>,它基本上只是堆栈分配数组的包装器。 C ++还有一个类std::vector<type>,它是堆分配数组的包装器(就像你在Java中习惯的那样),但它也具有ArrayList类功能。

在您的情况下,编写逻辑上和语义上与您的代码完全相同的代码是:

std::vector<int> array(10, 0); //EDIT: I added the second parameter because I don't think all implementations zero the memory when allocating it. This ensures that the memory is zeroed before use, like it would be in Java.
std::cout << array.size() << std::endl;
std::cout << array[5] << std::endl;
array[5] = 11;
std::cout << array[5] << std::endl;

尽管如此,我不会将变量命名为array,因为这可能令人困惑。