Reputation: 55
I'm trying to understand how bounded arrays work in C++. I need to have a quick length method to return the size of my bounded array. In Java I would do something like that:
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
If possible I would like to use an object array (i.e. a class implementing an array functionality) instead of pointers. Would I be correct to say that it feels much more natural to use an object array instead of a memory pointer to work with arrays?
Upvotes: 1
Views: 1349
Reputation: 20396
C++ has a class std::array<type, size>
which is basically just a wrapper for stack-allocated arrays. C++ also has a class std::vector<type>
which is a wrapper for heap-allocated arrays (like what you're used to in Java) but which also has ArrayList
-like functionality.
In your case, writing code which is logically and semantically identical to yours is:
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;
Though, I wouldn't name the variable array
, since that could be confusing.
Upvotes: 2