[英]What's the correct way to work with bounded arrays in C++?
我试图了解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
,因为这可能会造成混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.