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

What's the correct way to work with bounded arrays in C++?

本文关键字:方法 是什么 数组 C++      更新时间:2023-10-16

我试图了解有界数组在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

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

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,因为这可能会让人感到困惑。